<template>
	<view class="content1 f-dc">
		<u-navbar :fixed="false" :title="titleName" :autoBack="false" :safeAreaInsetTop="true">
			<view slot="left" class="x-f">
				<u-icon name="arrow-left" color="#fff" size="20" @click="goBack"></u-icon>

				<u-icon name="close" color="#fff" size="20" style="margin-left: 20px;"
					@click="goBack('close')"></u-icon>
			</view>
			<view slot="right">
				<m-bubble type="list" :selectData="formMenus" position="right" topOpsotion="right" bgcRgba="#fff"
					color="#333" @selectFun="TapPopup">
					<u-icon name="more-dot-fill" color="#fff" class="moremenu"></u-icon>
				</m-bubble>
			</view>
		</u-navbar>
		<view class="MainBox1" v-if="isShowMainForm" :style="{flex: childFormList.length ? 'none' : 1}">
			<u--form labelPosition="left" :model="formData" ref="uForm" labelWidth="100"
				:labelStyle="{fontSize:'14px',fontWeight:600}">
				<u-form-item labelWidth="100" :label="row.baseProperty.labelName" prop="name" borderBottom
					:required="row.baseProperty.isRequired" v-if="row.baseProperty.controlType != 'hidden'"
					v-for="(row,index) in formDesign" :key="index">

					<view v-if="row.baseProperty.controlType == 'datepicker'" @click="clickDatePicker(row)"
						style="width:100%">
						<u--input v-model="formData[row.baseProperty.controlName]" :ref="row.baseProperty.controlName"
							:readonly="true" border="none" v-if="row.baseProperty.controlType == 'datepicker'"
							suffixIcon="calendar"></u--input>
					</view>
					<view v-else-if="row.baseProperty.controlType=='select' && row.controlProperty.select.type == 1"
						@click="openBaseScreen(row)" style="width:100%">
						<u--input v-model="formData[row.baseProperty.controlName+'_show']"
							:name="row.baseProperty.controlName" suffixIcon="arrow-right" border="none"
							:readonly="true"></u--input>
					</view>
					<view v-else-if="row.baseProperty.controlType=='select' && row.controlProperty.select.type == 3"
						@click="openBaseScreen(row)" style="width:100%">
						<u--input v-model="formData[row.baseProperty.controlName+'_show']"
							:name="row.baseProperty.controlName" suffixIcon="arrow-right" border="none"
							:readonly="true"></u--input>
					</view>
					<u--input type="number" v-model="formData[row.baseProperty.controlName]" @change="dataChange(row)"
						:name="row.baseProperty.controlName" border="none" :readonly="row.baseProperty.isReadOnly"
						v-else-if="row.baseProperty.controlType == 'number'"
						:suffixIcon="row.baseProperty.isReadOnly ? '' : 'edit-pen-fill'"></u--input>
					<u-textarea v-model="formData[row.baseProperty.controlName]" :name="row.baseProperty.controlName"
						border="none" :readonly="row.baseProperty.isReadOnly" @change="dataChange(row)"
						v-else-if="row.baseProperty.controlType == 'textarea'"
						:suffixIcon="row.baseProperty.isReadOnly ? '' : 'edit-pen-fill'"></u-textarea>
					<u--input type="text" v-model="formData[row.baseProperty.controlName]"
						:name="row.baseProperty.controlName" border="none" :readonly="row.baseProperty.isReadOnly"
						@change="dataChange(row)" v-else-if="row.baseProperty.controlType == 'textbox'"
						:suffixIcon="row.baseProperty.isReadOnly ? '' : 'edit-pen-fill'"></u--input>
					<view v-else-if="row.baseProperty.controlType=='fileUpload'" style="width:100%">

						<cl-upload v-model="formData[row.baseProperty.controlName + '_show']" useBeforeDelete
							@beforeDelete="beforeDelete" :uploadKey="row.baseProperty.controlName"
							:listStyle="{columns: BoxInfoCallBack.num,height:BoxInfoCallBack.height+'rpx',padding:'6px',columnGap:'10px',rowGap:'10px'}"
							cloudType="other" :action="uploadFile_action" @onSuccess="onSuccess"></cl-upload>
					</view>
				</u-form-item>
			</u--form>
		</view>
		<u-gap height="1" bgColor="#dadada"></u-gap>
		<!-- <view class="f-dc" :class="isShowMainForm?'DetailBox':'DetailBoxFull'"> -->
		<view class="f-dc" style="overflow: auto;" :style="{flex: childFormList.length ?   1:'none'}">
			<!-- <u-icon name="order" ></u-icon> -->
			<!-- 导入数据，添加子表 -->


			<u-sticky bgColor="#fff" zIndex="11">
				<view class="x-bc">
					<u-row customStyle="margin-bottom: 10px;flex :1;overflow: auto hidden;"
						v-if="importConfig && filterImportConfigList().length>0">
						<u-col :span="12/(filterImportConfigList().length <= 4 ? filterImportConfigList().length : 4)"
							v-for="importItem in filterImportConfigList()"
							style="display: flex;justify-content: center;align-items: center;">
							<u-icon name="order" color="#51d0d0" size="20" style="padding:10px 0px 0px 5px;"
								:label="importItem.btnName" labelSize="14" labelColor="#51d0d0"
								@click="importData(importItem)"></u-icon>
						</u-col>
					</u-row>

					<view v-if="filterImportConfigList().length > 4" @click="openImportSheet"
						style="height: 100%;width: 50px;border-left: 1px solid #e8e8e8;opacity: 0.8;" class="x-c">
						<u-icon name="grid-fill" color="#555555" size="28"></u-icon>
					</view>

				</view>
				<u-gap height="1" bgColor="#dadada" v-if="importConfig && filterImportConfigList().length>0"></u-gap>
				<u-tabs :list="TabList" keyName="title" :current="tabCurrent" @click="clickTabItem"></u-tabs>

			</u-sticky>
			<!-- <view :class="isShowMainForm?'Main_CardListBox':'Main_CardListBoxFull'" -->
			<view v-for="(childForm,index) in childFormList">
				<u-empty mode="history" text="列表数据为空" marginTop="50"
					v-if="childForm.tableData && childForm.tableData.length==0 && childForm.title == TabList[tabCurrent]['title']">
				</u-empty>

				<u-swipe-action v-show="childForm.title == TabList[tabCurrent]['title']">
					<u-swipe-action-item :options="deleteOper"
						v-for="(item,idx) in childApproveShowFun(childForm.tableData)" :name="idx"
						@click="delRow(childForm,item)" ref="delSwiper" style="margin-bottom: 10rpx;">
						<view class="content_main_CardBox" @click="openEditWin(item,childForm,idx)">
							<view class="FiledBox">
								<view v-if="childForm.hasOwnProperty('titleCol')">
									<text class="FiledBox_label_f18" v-if="childForm.titleCol.colType!=2"><text
											class="van-badge">{{ idx+1 }}</text>
										{{ item[childForm.titleCol.colName]}}</text>
									<text class="FiledBox_label_f18" v-else="childForm.titleCol.colType==2"><text
											class="van-badge">{{ idx+1 }}</text>
										{{ showActualValue(item[childForm.titleCol.colName],childForm.titleCol ) }}</text>
								</view>

								<view v-else>
									<text class="FiledBox_label_f18"><text class="van-badge">{{ idx+1 }}</text></text>
								</view>

							</view>
							<view style="clear: both;"></view>
							<view class="content_main_CardBox_RightTop y-end"
								style="position: absolute;right: 20rpx;top: 50%;">
								<view class="FiledBox">
									<u-icon name="arrow-right"></u-icon>
								</view>
							</view>

							<view class="FiledBox" v-for="col in childForm.columns"
								v-if="!col.isHidden && !col.isTitle">
								<text style="color:red"
									:style="{visibility: col.isRequired ? 'initial':'hidden'}">*</text>
								<text class="FiledBox_label_f14 FiledBox_grifola">{{ col.colDesc }}:</text>
								<text class="FiledBox_value FiledBox_value_f14 FiledBox_grifola"
									v-if="col.colType==5">{{showFileTheNumFun(item[col.colName])}}</text>
								<text class="FiledBox_value FiledBox_value_f14 FiledBox_grifola"
									v-else-if="col.colType!=2">{{item[col.colName] }}</text>
								<text class="FiledBox_value FiledBox_value_f14 FiledBox_grifola"
									v-else-if="col.colType==2">{{showActualValue(item[col.colName],col) }}</text>
							</view>
						</view>
						<view class="childBtns">
							<u-button v-for="work in childForm.workList" color="#51d0d0"
								v-if="btn_showConditionByChild(work)" @click="selfChildWorkHandler(work,item)"
								type="primary" size="small" :text="work.name"
								style="width:auto;margin-right:10px;"></u-button>
						</view>
					</u-swipe-action-item>
				</u-swipe-action>
			</view>
		</view>


		<view class="content_bottom1 x-ec" :style="$utils.disposeSafeBottomFun()">

			<button v-if="!isUpdate && enabledSubmitBtn" class="CommonBtnSize workBtn" plain
				:disabled="!enabledSubmitBtn" @click="saveDraftInfo">保存草稿</button>

			<!-- 审批流 -->
			<button class="CommonBtnSize workBtn" plain style="margin-left: 10px;" :disabled="!enabledSubmitBtn" v-if="approvalConfig.isEnableApproval && (!formData.Status || formData.Status==3) && !formData.Approve  &&
				workList.filter(function(item){ return item.name=='发起审批' }).length==0" @click="startApprove">
				<text>发起审批</text>
			</button>

			<button class="CommonBtnSize workBtn" plain style="margin-left: 10px;" @click="formApprove"
				:disabled="!enabledSubmitBtn"
				v-if="approvalConfig.isEnableApproval && formData.Status == 1 && isCurApproval">
				<text>审批单据</text>
			</button>

			<button class="CommonBtnSize workBtn" plain style="margin-left: 10px;" @click="cancelApprove"
				:disabled="!enabledSubmitBtn" v-if="approvalConfig.isEnableApproval && formData.Status == 1">
				<text>撤销审批</text>
			</button>

			<!-- content_bottom_primary_Btn -->
			<!-- <button class="CommonBtnSize workBtn" plain v-for="btn in workList" style="margin-left: 10px;"
				v-if="btn_showCondition(2,btn)" @click="selfWorkHandler(btn)">
				{{ btn.name }}
			</button> -->

			<!-- 当业务按钮存在一项时 -->
			<view v-if="MoreSheetList.length == 1 && btnAllowShowFun(MoreSheetList[0]['name'])">
				<button class="CommonBtnSize workBtn x-c" :class="buttonClasses" :style="buttonStyles"
					:disabled="!enabledSubmitBtn" plain v-for="btn in MoreSheetList" style="margin-left: 10px;"
					@click="selfWorkHandler(btn)">
					{{ btn.name }}
				</button>
			</view>
			<!-- 当存在多项业务按钮时 -->
			<view v-else-if="MoreSheetList.length > 1">
				<u-button class="CommonBtnSize content_bottom_primary_plainBtn" style="margin-left: 10px;"
					@click="openMoreSheet" :disabled="!enabledSubmitBtn" text="更多"></u-button>
			</view>

			<view>
				<button class="CommonBtnSize content_bottom_primary_Btn" :disabled="!enabledSubmitBtn"
					style="margin-left: 10px;" v-if="!isUpdate && btn_showCondition(1,'新增') && btnAllowShowFun('新增')"
					@click="saveRow">提交</button>
				<button class="CommonBtnSize content_bottom_primary_Btn" :disabled="!enabledSubmitBtn"
					style="margin-left: 10px;" v-if="isUpdate && btn_showCondition(1,'编辑') && btnAllowShowFun('编辑')"
					@click="saveRow">提交</button>
			</view>
		</view>
		<!-- 日期控件 -->
		<u-datetime-picker style="z-index: 9999999;" :maxDate="maxOickerDateTime" :show="showDatePicker"
			v-model="curDate" :mode="DateFormatType" :formatter="formatterDate" @confirm="onDatePickerConfirm"
			@cancel="showDatePicker=false,curDate=''" :closeOnClickOverlay="true"></u-datetime-picker>
		<u-datetime-picker style="z-index: 9999999;" :maxDate="maxOickerDateTime" :show="showDatePicker2"
			v-model="curDate2" :mode="DateFormatType2" :formatter="formatterDate" @confirm="onDatePickerConfirm2"
			@cancel="showDatePicker2=false,curDate2=''" :closeOnClickOverlay="true"></u-datetime-picker>
		<!-- 弹出框 -->
		<!-- <u-popup :show="showEditWin" mode="bottom" @close="closeEditWin"> -->

		<uni-popup ref="EditWinPopup" type="bottom" @close="closeEditWin" @maskClick="closeEditWin"
			background-color="#fff" border-radius="10px 10px 0 0">

			<u-navbar v-if="!$utils.isPda()" :fixed="false" :autoBack="false" :safeAreaInsetTop="false" left-icon=" ">
				<view slot="right" class="x-ec">
					<u-icon name="reload" @click="TapPopup({name:'子表刷新'})" color="#fff" size="28"></u-icon>
					<u-icon name="scan" @click="TapPopup({name:'扫码'})" color="#fff" size="28"></u-icon>
				</view>
			</u-navbar>
			<view class="editDetail f-dc" :style="$utils.disposeSafeBottomFun()">
				<view style="flex:1;overflow: auto;width: 100%;padding: 10px 10px 10px 15px;">
					<u--form labelPosition="left" :model="editValues" ref="dForm" labelWidth="100">
						<view v-for="(row,index) in editFrame.columns">

							<u-form-item :label="row.colDesc" borderBottom :required="row.isRequired"
								v-show="!row.isHidden">

								<view v-if="row.colType==3" @click="clickDatePicker2(row)" style="width:100%">
									<u--input v-if="row.colType==3" v-model="editValues[row.colName]" readonly
										:ref="row.colName" inputAlign="right" border="none"></u--input>
								</view>
								<view v-else-if="row.colType==2  && row.selDetail.type==1" @click="openBaseScreen2(row)"
									style="width:100%">
									<u--input :value="showActualValue(editValues[row.colName],row)" inputAlign="right"
										:name="row.colName" :suffixIcon="row.isReadOnly ? 'none' : 'arrow-right'"
										border="none" :readonly="true"></u--input>
								</view>
								<view v-else-if="row.colType==2  && row.selDetail.type==3" @click="openBaseScreen2(row)"
									style="width:100%">
									<u--input :value="showActualValue(editValues[row.colName],row)" inputAlign="right"
										:name="row.colName" :suffixIcon="row.isReadOnly ? 'none' : 'arrow-right'"
										border="none" :readonly="true"></u--input>
								</view>

								<u--input v-else-if="row.colType == 4" type="number" v-model="editValues[row.colName]"
									inputAlign="right" :name="row.colName"
									@change="itemDataChange(row,editValues,editFrame,editValues[row.colName])"
									border="none" :readonly="row.isReadOnly"
									:suffixIcon="row.isReadOnly ? 'none' : 'edit-pen-fill'"></u--input>

								<view v-else-if="row.colType == 1" style="width: 100%;">

									<u--input type="text" v-model="editValues[row.colName]" inputAlign="right"
										:name="row.colName"
										@change="itemDataChange(row,editValues,editFrame,editValues[row.colName])"
										border="none" :readonly="row.isReadOnly"
										:suffixIcon="row.isReadOnly ? 'none' : 'edit-pen-fill'"></u--input>

								</view>

								<view v-else-if="row.colType == 5" style="width: 100%;">
									<!-- <view class="x-ec">
										<u--image :showLoading="true" :src="FileTypeByName(editValues,row)" width="30px"
											height="30px"></u--image>

										<u-tag text="查看附件" @click="FilePathView(editValues,row)" type="primary" plain
											plainFill size="mini" style="margin-left: 10px;"></u-tag>
									</view> -->
									<cl-upload v-model="editValues[row.colName + '_show']" useBeforeDelete
										@beforeDelete="beforeDeleteByChild" :uploadKey="row.colName"
										:listStyle="{columns: BoxInfoCallBack.num,height:BoxInfoCallBack.height+'rpx',padding:'6px',columnGap:'10px',rowGap:'10px'}"
										cloudType="other" :action="uploadFile_action"
										@onSuccess="onSuccessByChild"></cl-upload>
								</view>
							</u-form-item>

						</view>


					</u--form>

				</view>
				<view style="height: 70px;">
					<button class="CommonBtnSize content_bottom_primary_Btn"
						style="margin: 10px auto 0;width:calc(100% - 40px); " @click="closeEditWin">确定</button>
				</view>
			</view>

		</uni-popup>
		<!-- </u-popup> -->
		<!-- pda_tc80 -->
		<m-pda-scancode v-if="$utils.isPda()" :listenName="pdaListenCurrent"
			:SetContent="{action:$store.state.systemConfig.sysDeviceInfo.broadcastAction,extra:$store.state.systemConfig.sysDeviceInfo.broadcastResult}"></m-pda-scancode>


		<m-loading text="正在渲染" v-model="showMLoading" :showClose="false"
			maskBackgroundColor="rgba(0,0,0,0.3)"></m-loading>

		<u-action-sheet :actions="MoreSheetList" safeAreaInsetBottom :closeOnClickOverlay="true" cancelText="取消"
			:closeOnClickAction="true" @select="selfWorkHandler" :show="showMoreSheet"
			@close="closeSheetBtn"></u-action-sheet>

	</view>
</template>

<script>
	import ApprovalFuns from '@/common/comFun/ApprovalFun.js';

	var ApprovalFun = ApprovalFuns;


	import layerFun from '@/common/comFun/layerFun.js';
	var layer = layerFun;

	// 配合二开脚本使用APP.ajsx
	import APPFun from '@/common/comFun/APPFun.js';
	var APP = APPFun;

	import UseSqlite from '@/uni_modules/mc-ui/components/m-sqlite/js_sdk/sqlite-use.js';
	var UseSqliteFun = UseSqlite;

	import {
		taskManager
	} from '@/common/http/taskQueue.js';
	const open = uni.requireNativePlugin("Html5App-openFile");
	// var vm;
	const plug = uni.requireNativePlugin('Html5app-Gprinter');
	export default {
		data() {
			return {
				isFormModified: false, // 当前表单是否进行修改
				isShowingConfirm: false, // 防止重复弹窗
				backNum: 1, // 默认返回页数
				btnStyle: {
					width: 79,
					height: 40
				},
				showMLoading: false,
				routePageCurrent: 0, // 当前页面栈位置
				origin: '', // 来源界面
				idByDraftList: '', // 主键id，；来源-草稿箱
				titleName: '编辑',
				detailName: '',
				physicalTableName: '',
				keyName: '',
				keyValue: '',
				mainTitle: '',
				mainForm: [],
				tagForm: [],
				formData: {
					name: "测试"
				},
				editValues: {},
				formMenus: [{
						name: '隐藏表头',
						value: '',
						icon: 'order'
					},
					{
						name: '扫码',
						value: '',
						icon: 'scan'
					},
					{
						name: '刷新',
						value: '',
						icon: 'reload'
					}
				],

				pageWhere: [0, 0, 0], // 记录切换tab后，前一项所在位置
				tabCurrent: 0, // 选中tab项索引
				TabList: [],
				childFormList: [],
				changeDataSource: [],
				workList: [],
				crudList: [],
				importConfig: [],
				formDesign: [],
				isShowMainForm: true,
				showEditWin: false,
				editFrame: {},
				childOpenIndex: 0, // 被打开的索引数据
				//下拉控件
				windowSelectType: 1,
				curSelectWindowObj: {},
				curSelectWindowObj2: {},

				//日期控件
				DateFormatType: 'date', // 日期控件展示格式
				showDatePicker: false,
				curDate: '',
				curDateObj: '',
				DateFormatType2: 'date', // 日期控件展示格式
				showDatePicker2: false,
				curDate2: '',
				curDateObj2: '',
				isUpdate: false,
				enabledSubmitBtn: false,
				deleteOper: [{
					icon: 'trash-fill',
					style: {
						backgroundColor: '#ff0000',
						color: '#fff'
					}
				}],
				scanConfig: null, // 扫码配置
				printConfig: null, //打印配置
				onReadyCallBack: null, // 加载完成后
				childListData: [], // 加载完成后插入的数据
				waitKeyName: '',
				columns: [],
				childObj: {},
				tableKeyName: '', //表名

				uploadFile_action: '',
				uploadFileKey: '', // 文件上传字段

				showMoreSheet: false, // 更多按钮--操作菜单
				MoreSheetList: [],

				approvalConfig: {
					isEnableApproval: false
				},
				isCurApproval: false, // 判断是否为当前审批人
				ApprovalSort: null,
				globalData: {},
				isShowComApproval: false,

				approveObj: {},
				ApprovalID: null, // 审批ID

				APPRoleCol: [], // 主表单隐藏字段
				APPRoleColChildList: [], // 子表权限隐藏字段


				menuDetailObj: {},
				BoxInfoCallBack: {
					num: 3,
					height: 100
				},
			};
		},

		computed: {
			UserInfo() {
				return this.$store.state.UserInfo;
			},
			buttonClasses() {
				return {
					'small-font': this.btnStyle.width < 80,
					'disabled': !this.enabledSubmitBtn
				}
			},
			buttonStyles() {
				return {
					height: this.btnStyle.height ? `${this.btnStyle.height}px` : 'auto',
					'line-height': '20px'
				}
			},
			maxOickerDateTime() { // 日期控件最大时间
				let now = new Date();

				// 增加一百年  
				now.setFullYear(now.getFullYear() + 100);

				// 将Date对象转换为时间戳  
				return now.getTime();
			},
			pdaListenCurrent() { // pda监听器名称
				let routes = getCurrentPages(); //当前页面栈
				// pda监听器
				return "pdaScanCode" + routes.length;
			},
			selectPicker_formEditCurrent() { // pda监听器名称
				let routes = getCurrentPages(); //当前页面栈
				// pda监听器
				return "selectPicker_formEdit" + routes.length;
			},
			importDataCurrent() { // pda监听器名称
				let routes = getCurrentPages(); //当前页面栈
				// pda监听器
				return "importData" + routes.length;
			},
		},
		onLoad(option) {
			var that = this;
			let vm = this;

			let routes = getCurrentPages(); //当前页面栈
			this.routePageCurrent = routes.length;


			// 定义文件上传的IP
			this.uploadFile_action = this.Request.IPAgreement() + this.Request.serverIP() + '/FileData/UploadSignleFile';
			//详情页对象名称
			let menuDetailObj = this.$utils.deepClone(this.$store.state.MenuDetail);
			this.menuDetailObj = menuDetailObj;
			const {
				id, // 草稿主键ID
				detailName,
				keyName,
				keyValue,
				detailTitle,
				dataInfo: {
					titleColName,
					showColumnsInfo,
					tagColumnsInfo,
					childListData = [], // 给待办用的
					waitKeyName = "", // 给待办用的
				}
			} = menuDetailObj;

			// 判断是否存在传入值，origin 定义为 来源
			if (!this.$utils.isEmpty(option)) {
				// 判断来源
				if (option.origin == 'draft') { // 草稿箱
					this.origin = 'draft';

					this.idByDraftList = id; // 赋值草稿主键ID
				} else if (option.origin == 'approveWaitList') { // 审批待办
					this.origin = 'approveWaitList';
				}
			}

			// 设置基础数据信息
			that.detailName = detailName;
			that.keyName = keyName;
			that.keyValue = keyValue;
			that.titleName = detailTitle.replace('列表', '') + '编辑';
			that.mainTitle = titleColName;
			that.mainForm = showColumnsInfo;
			that.tagForm = tagColumnsInfo;

			// 给待办用的，暂时这么写
			that.childListData = childListData;
			that.waitKeyName = waitKeyName;

			// 获取用户信息，定义本地数据库表名
			let UserInfo = that.UserInfo;
			// 设置本地数据库表名
			that.tableKeyName = 'appAccount_' + UserInfo.Business + '_' + UserInfo.UserID;
			// 开启数据库
			that.openSQL();
			// 正在渲染页面数据
			that.initConfig(that.detailName);
		},
		onShow() {
			let vm = this;
			// 	let that = this;
			// 	let routes = getCurrentPages(); //当前页面栈
			// 	console.log(routes.length);
			// 	try {

			// 		if (vm) {
			// 			setTimeout(() => {

			// 				Object.assign(vm.$data, that.$data);
			// 			}, 300)
			// 		}
			// 	} catch (error) {
			// 		//TODO handle the exception
			// 	}
		},
		onReady() {
			let vm = this;
			let that = this;

			let routes = getCurrentPages(); //当前页面栈

			// PDA扫码监听器回调
			uni.$on("pdaScanCode" + routes.length, function(content) {
				// Object.assign(vm.$data, that.$data);
				vm.dealScan(content);
			})
			//弹窗下拉数据选择监听器
			uni.$on("selectPicker_formEdit" + routes.length, function(data) {

				// 判定当前页面已进行修改
				vm.isFormModified = true;

				var ret = data.data;
				//主表表单选择
				if (vm.windowSelectType == 1) {
					if (ret) {
						vm.formData[vm.curSelectWindowObj.baseProperty.controlName] = ret[vm.curSelectWindowObj
							.controlProperty.select.hiddenValue];
						//vm.formData[vm.curSelectWindowObj.baseProperty.controlName + '_show'] = ret[vm.curSelectWindowObj.controlProperty.select.displayValue];
						vm.$set(vm.formData, vm.curSelectWindowObj.baseProperty.controlName + '_show', ret[vm
							.curSelectWindowObj.controlProperty.select.displayValue]);

						vm.dataChange(vm.curSelectWindowObj, ret);
						vm.curSelectWindowObj = '';
					} else {
						vm.formData[vm.curSelectWindowObj.baseProperty.controlName] = '';
						vm.$set(vm.formData, vm.curSelectWindowObj.baseProperty.controlName + '_show', '');
						vm.dataChange(vm.curSelectWindowObj, ret);
						vm.curSelectWindowObj = '';
					}
					vm.$forceUpdate();
				} else if (vm.windowSelectType == 2) {
					if (ret) {
						console.log(vm.curSelectWindowObj2.colName);
						//vm.formData[vm.curSelectWindowObj.baseProperty.controlName + '_show'] = ret[vm.curSelectWindowObj.controlProperty.select.displayValue];
						vm.editValues[vm.curSelectWindowObj2.colName] = ret[vm.curSelectWindowObj2.selDetail
							.hiddenValue];
						vm.$set(vm.editValues, vm.curSelectWindowObj2.colName, ret[vm.curSelectWindowObj2
							.selDetail.hiddenValue]);
						vm.editValues[vm.curSelectWindowObj2.colName + '_show', ret[vm.curSelectWindowObj2
							.selDetail.displayValue]];
						vm.$set(vm.editValues, vm.curSelectWindowObj2.colName + '_show', ret[vm.curSelectWindowObj2
							.selDetail.displayValue]);
						console.log(vm.editValues);
						vm.itemDataChange(vm.curSelectWindowObj2, vm.editValues, vm.editFrame, ret);
						vm.curSelectWindowObj2 = '';
					} else {
						vm.editValues[vm.curSelectWindowObj2.colName] = '';
						vm.$set(vm.editValues, vm.curSelectWindowObj2.colName + '_show', '');
						vm.itemDataChange(vm.curSelectWindowObj2, vm.editValues, vm.editFrame, ret);
						vm.curSelectWindowObj2 = '';
					}
					vm.refreshEditValueCol(vm.editFrame);
					vm.$forceUpdate();
				}
			})

			// 导入数据监听器
			uni.$on("importData" + routes.length, function(importValue) {
				// console.log('测试是否会在初始化的时候触发输入框change事件');
				// 判定当前页面已进行修改
				vm.isFormModified = true;
				let columns = importValue.columns;
				let selections = importValue.selections;

				var colToColumnList = columns.filter(function(item) {
					return item.colToColumn != undefined && item.colToColumn !== ""
				});
				var isMain = false;
				var mainCount = 0;
				var childFormDatas = [];

				for (var z = 0; z < vm.childFormList.length; z++) {
					childFormDatas.push({
						name: vm.childFormList[z].title,
						frameName: vm.childFormList[z].name,
						record: []
					});
				};
				for (var i = 0; i < selections.length; i++) {
					for (var j = 0; j < colToColumnList.length; j++) {
						var toColumnNames = colToColumnList[j].colToColumn.split(',');
						for (var k = 0; k < toColumnNames.length; k++) {
							var nameKey = toColumnNames[k].split('.')[0];
							var nameValue = toColumnNames[k].split('.')[1];
							//主记录数据
							if (nameKey == "main" && !isMain) {
								mainCount++;
								if (vm.formData[nameValue] != undefined) {
									vm.formData[nameValue] = selections[i][colToColumnList[j].colName];
									//vm.execChangeEvent(colToColumnList[j].colName, 1);
									//vm.execChangeEvent(colToColumnList[j].colName, 2);
								}
							}
							if (nameKey != "main") {
								var recordList = childFormDatas.filter(function(item) {
									return item.name == nameKey || item.frameName == nameKey
								});
								if (recordList.length > 0) {
									for (var r = 0; r < recordList.length; r++) {
										if (recordList[r].record[i] == undefined) {
											recordList[r].record[i] = {};
										}
										recordList[r].record[i][nameValue] = selections[i][colToColumnList[j]
											.colName
										];
									}
								}
							}
						}
					}
					if (mainCount > 0) {
						isMain = true;
					}
				}
				// vm.refreshInitActualName();
				// console.log(childFormDatas)
				//插入子表数据
				for (var i = 0; i < childFormDatas.length; i++) {
					if (childFormDatas[i].record.length > 0) {
						if (JSON.stringify(childFormDatas[i].record) != "{}") {
							//插入子表
							vm.insertImportData(childFormDatas[i].frameName, childFormDatas[i].record);
						}
					}
				}
			});



			// 监听审批待办触发后，回调的数据
			uni.$on("emitNextItem", function(data) {
				if (data.listType == "next") { // 存在下一条数据

					if (data.nextData.Url) {
						const queryString = data.nextData.Url;
						const params = queryString.split('&').reduce((acc, current) => {
							const [key, value] = current.split('=');
							acc[key] = decodeURIComponent(value); // 解码URL编码的字符  
							return acc;
						}, {});


						let returnData = {
							detailTitle: params.objName,
							detailName: params.objName,
							keyName: params.keyName,
							keyValue: params.keyValue,
							dataInfo: {
								titleColName: '',
								showColumnsInfo: [],
								tagColumnsInfo: [],
							}
						};
						that.$store.commit('ChangeAndSetStateData', {
							Name1: 'MenuDetail',
							data: returnData
						});

						setTimeout(() => {
							uni.redirectTo({
								url: '/commonPage/Form/Edit' + '?origin=approveWaitList',
							});
						}, 300)
					}
				} else if (data.listType == "lastData") { // 已是最后一条数据
					layer.alert("当前已是最后一条数据")

				} else if (data.listType == "null") { // 未找到数据
					layer.alert("当前数据已丢失，请返回列表刷新", function() {
						uni.navigateBack();
					})
				}

			})

		},
		mounted() {
			let that = this;

			setTimeout(() => {
				// uni.createSelectorQuery().select('.uploadBox').boundingClientRect(data => {
				let getSystemInfoSync = uni.getSystemInfoSync();
				let backData = that.$utils.calculateAdaptiveLayout(getSystemInfoSync.screenWidth, 20)
				that.BoxInfoCallBack = backData;
				// }).exec();
			}, 300)

			that.$nextTick(() => {
				setTimeout(() => {

					uni.createSelectorQuery().select('.CommonBtnSize').boundingClientRect(rect => {
						// that.btnStyle = rect
						Object.assign(that.btnStyle, rect)
					}).exec();
				}, 300)
			})

			// 组件中监听队列完成
			this.$onQueueEvent('queueEmpty', () => {
				// 当所有事件加载完成后：
				// 开放按钮点击权限
				that.$utils.hideLoading();
				this.showMLoading = false;
				that.enabledSubmitBtn = true; // 解开按钮限制
			});

			this.$onQueueEvent('requestStart', (ret) => {});
			this.$onQueueEvent('requestSuccess', (ret) => {});
			// this.$onQueueEvent('queueChange', (ret) => {
			// 	console.log(ret);
			// });
			this.$onQueueEvent('requestFail', (ret) => {
				console.log(ret);
				// 当所有事件加载完成后：
				// 开放按钮点击权限
				if (ret.detail.status == 500) {
					let msg = ret.detail.msg || "接口请求异常，请点击刷新或退出";
					layer.confirm(msg, {
						title: "提示",
						confirmText: "刷新",
						cancelText: "退出",
					}, function(ret) {
						if (ret.action == 'confirm') {
							that.initConfig(that.detailName);
						} else if (ret.action == 'cancel') {
							that.goBack();
						}

					});
				} else {
					layer.confirm(JSON.stringify(ret), {
						title: "请求失败，点击刷新或退出",
						confirmText: "刷新",
						cancelText: "退出",
					}, function(ret) {
						if (ret.action == 'confirm') {
							that.initConfig(that.detailName);
						} else if (ret.action == 'cancel') {
							that.goBack();
						}

					});
				}

			});
		},
		beforeDestroy() {
			if (this.$requestQueue) {
				this.$requestQueue.destroy();
			}
			// this.$offQueueEvent('queueEmpty');
		},
		onUnload() {
			let vm = this;
			// vm.$store.commit('ChangeAndSetStateData', {
			// 	Name1: 'MenuDetail',
			// 	data: {}
			// });
			// 注销pda扫码监听事件
			uni.$off(this.pdaListenCurrent);
			// 注销导入监听事件
			uni.$off(this.importDataCurrent);
			// 注销弹窗下拉数据选择监听事件
			uni.$off(this.selectPicker_formEditCurrent);
			// 注销审批待办监听器
			uni.$off("emitNextItem");

		},
		onBackPress(options) { // 页面生命周期钩子
			if (this.isFormModified) {
				return this.showBackConfirm() // 显示确认弹窗
				// return true // 拦截返回操作（关键步骤）
			}
			// 未修改则正常返回
			return false
		},
		// onBackPress(options) { // 监听页面返回
		// 	console.log(options)
		// 	let that = this;
		// 	if (options.from == 'backbutton' || options.from == 'navigateBack') {
		// 		// 判断当前页面是否修改
		// 		if (that.isFormModified) {
		// 			layer.confirm('当前页面已修改，是否确认退出？', function(ret) {
		// 				if (ret.action == "confirm") {
		// 					// return false;
		// 					uni.navigateBack({
		// 						delta: that.backNum
		// 					})
		// 					return false;
		// 				} else {
		// 					return true;
		// 				}
		// 			})
		// 			return true;
		// 		} else {

		// 			return false
		// 		}
		// 	} else {
		// 		return false;
		// 	}
		// },
		methods: {
			showBackConfirm() {
				let that = this;
				if (this.isShowingConfirm) return;
				let backType = true;
				this.isShowingConfirm = true;
				layer.confirm('当前页面已修改，是否确认退出？', function(ret) {
					if (ret.action == "confirm") {
						backType = false;
						that.isShowingConfirm = false;
						that.isFormModified = false;
						uni.navigateBack({
							delta: that.backNum
						});
					} else {
						that.isShowingConfirm = false;
					}
				})
				return backType;
			},
			processImageUrl(url) { // 处理图片链接地址
				if (uni.$m.utils.isEmpty(url)) '';
				url = url.trim();

				function urlRegular(value) {
					return /^((https|http|ftp|rtsp|mms):\/\/)/
						.test(value)
				}

				let isHttp = urlRegular(url);
				if (isHttp) {
					return url;
				} else {
					return this.Request.IPAgreement() + this.Request.serverIP() + url;
				}

			},
			FilePathView(data, col) { // 预览文件
				let FileTypeBack = this.$utils.isFileType(data[col.colName]);
				switch (FileTypeBack) {
					case 'video':
						uni.navigateTo({
							url: '/commonPage/Form/video-preview' + '?url=' + this.processImageUrl(data[col
								.colName])
						})
						break;
					case 'image':
						// 查看图片
						uni.previewImage({
							current: 0,
							urls: [this.processImageUrl(data[col.colName])],
							success() {},
							fail(err) {
								console.log(err);
							}
						})
						break;
					default:
						// 预览文件
						uni.downloadFile({
							url: this.processImageUrl(data[col.colName]),
							success: function(res) {
								var filePath = plus.io.convertLocalFileSystemURL(res.tempFilePath);
								console.log(JSON.stringify(filePath))
								open.openFile({
									filename: filePath,
									title: "预览文件",
									isShowBackIcon: true
								}, ret => {

								})
							}
						})
						break;
				};
			},
			FileTypeByName(data, col) {
				let FileTypeBack = this.$utils.isFileType(data[col.colName]);
				let pathIcon = '';
				let path = '/static/assets/image/img/';
				let pathUrl = '';
				switch (FileTypeBack) {
					case 'image':
						pathIcon = 'image';
						break;
					case 'video':
						pathIcon = 'video';
						break;
					case 'text':
						pathIcon = 'txt';
						break;
					case 'pdf':
						pathIcon = 'pdf';
						break;
					case 'spreadsheet':
						pathIcon = 'xls';
						break;
					default:
						break;
				};
				if (this.$utils.isEmpty(pathIcon)) return '';
				pathUrl = path + pathIcon + '.png';
				return pathUrl;
			},
			btnShowCallBack(data, col) { // 临时--判断是否是文件

				let FileTypeBack = this.$utils.isFileType(data[col.colName]);
				let BtnBoolean = false;
				switch (FileTypeBack) {
					case false:
					case 'unknown':
						BtnBoolean = false;
						break;
					default:
						BtnBoolean = true
						break;
				};
				console.log(BtnBoolean);
				return BtnBoolean;
			},
			btnAllowShowFun(functionName) { // 判断当前按钮是否允许显示
				let vm = this;
				const {
					filterUnPermissionConfig = []
				} = this.$store.state.appConfigInfo;
				// 检查是否存在任何项的 FunName 与传入的字符串相匹配
				const isFunctionDenied = filterUnPermissionConfig.some(item => item.FunName === functionName);
				return !isFunctionDenied;
			},
			childApproveShowFun(data) { // 子表数据映射
				let vm = this;
				let that = this;
				try {
					if (!this.$utils.isEmpty(data)) { // 判断是否存在子表数据
						const appRoleColChildMap = that.APPRoleColChildList;
						data.forEach(item => {
							let colInfos = item.colInfo;
							colInfos.forEach(row => {
								const colName = row.colName; // 缓存colName，减少访问次数
								const typeInfo = appRoleColChildMap.get(colName); // 子表权限隐藏字段处理
								if (typeInfo) {
									// 调整字段配置数据
									const isViewRole = typeInfo.IsViewRole;
									const isEditRole = typeInfo.IsEditRole;
									row.isHidden = !isViewRole;
									row.isReadOnly = !isViewRole && !isEditRole;
								}
							});
						});
					};

				} catch (error) {
					//TODO handle the exception
				}

				return data || [];
			},
			goBack(str = 'back') { // 页面返回按钮事件处理
				let vm = this;
				let backNum = 1;

				if (str == 'close') { // 点击关闭
					let routes = getCurrentPages(); //当前页面栈

					let routePageCurrent = this.$store.state.appConfigInfo.routePageCurrent;

					backNum = routes.length - routePageCurrent; // 返回的页数


				}
				vm.backNum = backNum;
				uni.navigateBack({
					delta: backNum
				})

			},
			refreshPage() { // 刷新当前页、列表、详情
				let vm = this;

				// 监听器说明

				// 刷新详情页面、审批待办
				uni.$emit('refreshToIndex'); // 刷新详情
				uni.$emit('refreshToApprove'); // 刷新审批待办

				// 详情页面刷新，会触发列表页面刷新
				let hasListPage = vm.$utils.findPageInStack("/commonPage/Form/index");
				console.log(!hasListPage.exists);
				// 判断是否存在详情页面栈
				if (!hasListPage.exists) {
					// 当不存在详情页面时，手动触发列表刷新
					uni.$emit('FormInitToRefresh', { // 触发列表刷新
						keyID: vm.formData[vm.keyName]
					});
				}
				//刷新整体表单
				vm.initConfig(vm.detailName);
				if (!vm.isUpdate) {
					uni.$emit('refreshDraftInfo'); // 触发草稿刷新
				}
			},

			beforeDelete({ // 文件上传-删除指定数据事件
				fileToDelete,
				uploadKey
			}, index, next) {
				let vm = this;
				let that = this;
				uni.showModal({
					title: '提示信息',
					content: '确定要删除这个文件嘛？',
					success: res => {
						if (res.confirm) {
							let pathData = JSON.parse(JSON.stringify(that.formData[uploadKey + '_show']))
							pathData.splice(index, 1);
							that.formData[uploadKey] = pathData.map(item => item.path).join(',');
							// 判定当前页面已进行修改
							vm.isFormModified = true;

							setTimeout(() => {
								next();
							}, 300);
						}
					}
				});
			},
			onSuccess(data, uploadKey) { // 文件上传-上传成功事件
				let vm = this;
				let path = data.data;

				function startsWithHttp(url) {
					return url.startsWith('http://') || url.startsWith('https://');
				}
				if (!startsWithHttp(data.data)) {
					path = this.Request.IPAgreement() + this.Request.serverIP() + data.data;
				}

				this.formData[uploadKey + '_show'].push({
					path: path
				})
				/* this.formData[uploadKey] = this.formData[uploadKey + '_show'].map(item => {
					return item.path
				}); */

				let PathData = this.formData[uploadKey + '_show'].map(item => {
					return item.path
				});
				this.formData[uploadKey] = PathData.join(',');

				// 判定当前页面已进行修改
				vm.isFormModified = true;
			},
			beforeDeleteByChild({ // 文件上传-删除指定数据事件
				fileToDelete,
				uploadKey
			}, index, next) {
				let vm = this;
				let that = this;
				uni.showModal({
					title: '提示信息',
					content: '确定要删除这个文件嘛？',
					success: res => {
						if (res.confirm) {
							let pathData = JSON.parse(JSON.stringify(that.editValues[uploadKey + '_show']))
							pathData.splice(index, 1);
							that.editValues[uploadKey] = pathData.map(item => item.path).join(',');

							// 判定当前页面已进行修改
							vm.isFormModified = true;
							setTimeout(() => {
								next();
							}, 300);
						}
					}
				});
			},
			onSuccessByChild(data, uploadKey) { // 文件上传-上传成功事件
				let vm = this;
				let path = data.data;

				function startsWithHttp(url) {
					return url.startsWith('http://') || url.startsWith('https://');
				}
				if (!startsWithHttp(data.data)) {
					path = this.Request.IPAgreement() + this.Request.serverIP() + data.data;
				}

				this.editValues[uploadKey + '_show'].push({
					path: path
				})
				let PathData = this.editValues[uploadKey + '_show'].map(item => {
					return item.path
				});
				console.log(PathData);
				this.editValues[uploadKey] = PathData.join(',');
				console.log(this.editValues[uploadKey]);
				vm.refreshEditValueCol(vm.editFrame);
				// 判定当前页面已进行修改
				vm.isFormModified = true;
			},

			// 向列表页发起切换下一条数据的指令
			openNextPage() {
				if (this.origin == "approveWaitList") {
					uni.$emit('switch-to-next-item');
				}
			},

			// 审批流程按钮
			startApprove() { //判定是否启用审批流
				let vm = this;
				if (!vm.enabledSubmitBtn) {
					return;
				}
				vm.enabledSubmitBtn = false;
				ApprovalFun.startApprove(vm);
			},
			formApprove() { // 审批单据
				let vm = this;
				if (!vm.enabledSubmitBtn) {
					return;
				}
				vm.enabledSubmitBtn = false;
				ApprovalFun.formApprove(vm);
			},
			cancelApprove() { // 撤销审批
				let vm = this;
				if (!vm.enabledSubmitBtn) {
					return;
				}
				vm.enabledSubmitBtn = false;
				ApprovalFun.cancelApprove(vm);
			},


			// 打开数据库
			openSQL() {
				UseSqliteFun.openSQL()
			},
			async saveDraftInfo() { // 点击保存草稿按钮
				let vm = this;
				let that = this;
				that.$utils.showLoading();
				// 存储基础配置信息
				// 1、判断来源，如果是草稿箱来源，则删除数据库中该条数据，再插入
				if (!this.$utils.isEmpty(this.origin) && this.origin == 'draft' && !this.$utils.isEmpty(this
						.idByDraftList)) {
					// 删除本条数据
					await this.deleteTableData(this.idByDraftList);
				}

				let newTableData = [];

				if (that.childFormList[0].tableData.length) {
					let childFormList_DataCoopy = that.$utils.deepClone(that.childFormList[0])

					newTableData = childFormList_DataCoopy['tableData'].map(item => {
						item['colInfo'] = [];

						return {
							...item
						}
					})
				}
				let sql =
					'"id" INTEGER PRIMARY KEY AUTOINCREMENT,"detailTitle" text,"detailName" text,"keyName" text,"formData" text,"tableData" text,"CreatDate" text';

				let param = {
					dbTable: that.tableKeyName,
					sql: sql,
				}
				UseSqliteFun.creatSqlRow(param, function() {
					// 需要存储的数据

					let arr = [{
						detailTitle: that.titleName.replace('编辑', ''),
						detailName: that.detailName,
						keyName: that.keyName,
						formData: JSON.stringify(that.formData),
						tableData: JSON.stringify(newTableData),
					}]
					// 判断是否是草稿进来的，进行插入或更新数据
					that.insertTableData(arr);
					that.$utils.hideLoading();
				}, function(err) {
					that.$utils.hideLoading();
					layer.msg('保存失败');
				});

			},
			// 新增表数据
			insertTableData(arr) {
				let vm = this;
				let that = this;
				let open = UseSqliteFun.isOpen();
				if (open) {
					arr.map(item => {
						let time = that.$utils.dateFormat(new Date(), 'Y-MM-dd hh:mm:ss');
						let sql =
							`'${item.detailTitle}','${item.detailName}','${item.keyName}','${item.formData}','${item.tableData}','${time}'`;
						let condition = "'detailTitle','detailName','keyName','formData','tableData','CreatDate'";
						// 新增 DB.insertTableData(表名, 对应表头列的数据)

						let param = {
							dbTable: that.tableKeyName,
							sql: sql,
							condition: condition,
						};
						UseSqliteFun.insertSqlRow(param, function() {
							console.log("新增数据成功");
							// 发起监听，刷新草稿箱数据

							that.$utils.hideLoading();
							uni.showToast({
								title: '保存成功'
							});
							uni.$emit('refreshDraftInfo');
						}, function(error) {
							that.$utils.hideLoading();
							that.$utils.msg('保存失败');
							console.log("失败", error);
						});
					})
				} else {
					that.$utils.hideLoading();
					that.$utils.msg("数据库未打开");
				}
			},

			// 删除表数据
			deleteTableData(id) {
				let vm = this;
				let param = {
					dbTable: this.tableKeyName,
					key: "id",
					id: id
				}
				UseSqliteFun.deleteSqlRow(param, function() {
					vm.idByDraftList = '';
					uni.$emit('refreshDraftInfo'); // 触发草稿刷新
					vm.refreshPage();
				}, function(error) {
					vm.$utils.hideLoading();
					vm.$utils.msg('保存失败');
				});

			},



			childFormListFun() {
				let vm = this;

				if (vm.childFormList.length) {
					return 'none'
				} else {
					return 1
				}
			},
			TapPopup(data) {
				const {
					name
				} = data;
				const vm = this;

				switch (name) {
					case '隐藏表头':
					case '显示表头': {
						vm.isShowMainForm = name === '显示表头';
						vm.formMenus[0].name = vm.isShowMainForm ? '隐藏表头' : '显示表头';
						break;
					}
					case '扫码': {
						/* uni.scanCode({
							success: (res) => {
								// console.log(res)
								vm.dealScan(res.result);
							},
							fail: (err) => {
								console.error('扫码失败:', err);
								// layer.alert(err.errMsg)
							}
						}); */
						vm.$scanPopup.openScan({
							success: (res) => {
								vm.dealScan(res.result);
							}
						})
						break;
					}
					case '子表刷新': {
						vm.refreshEditValueCol(vm.editFrame);
						break;
					}
					case '刷新': {
						vm.initConfig(vm.detailName);
						break;
					}
					case '查阅审批流': {
						ApprovalFun.viewListApprove(vm);
						break;
					}
					case '打印机列表': {
						uni.navigateTo({
							url: '../Tool/printList'
						});
						break;
					}
					case '打印': {
						const connectDevice = uni.getStorageSync('connectDevice');
						if (connectDevice) {
							let maxData = [];
							eval(vm.printConfig); // 注意：eval 有安全风险，建议使用其他方式替代
							plug.printer({
								TSC: maxData
							}, (ret) => {
								// 处理打印结果
							});
						} else {
							uni.navigateTo({
								url: '../Tool/printList'
							});
						}
						break;
					}
					default:
						console.warn(`未处理的选项: ${name}`);
						break;
				}
			},
			clickTabItem(data) { // 点击Tab栏 
				let vm = this;
				let that = this;
				this.tabCurrent = data.index;

				// 根据APP表单名称获取所属权限。
				// console.log(vm.TabList[data.index]['name']);
				// 根据当前选中的表单tab项，获取需要隐藏的权限。
				try {

					// this.$store.dispatch('GetAPPRoleColFunByRoleID', {
					// 	moduleName: vm.TabList[data.index]['name'],
					// 	moduleType: 'formlist',
					// }).then(res => {
					// 	if (res.status == 200) {
					// 		that.APPRoleColChildList = new Map(res.data.ds.map(row => [row.ColName, row]));
					// 	}
					// }).catch((err) => {
					// 	console.log(err)

					// })
					that.$request("getAPPRoleColFunByRoleID", {
						moduleName: vm.TabList[data.index]['name'],
						moduleType: 'formlist',
					}, (res) => {
						if (res.status == 200) {
							// that.APPRoleColChildList = new Map(res.data.ds.map(row => [row.ColName, row]));
							that.APPRoleColChildList = new Map();
							if (Array.isArray(res?.data?.ds)) {
								for (const row of res.data.ds) {
									if (row?.ColName !== undefined) {
										that.APPRoleColChildList.set(row.ColName, row);
									}
								}
							}
						};
					})
				} catch (error) {
					//TODO handle the exception
				}

			},
			isShowColumns(colObj) {
				let vm = this;
				var that = this;
				var showColumns = uni.getStorageSync(that.moduleName + '_ShowColumns');
				var isShow = true;
				if (showColumns) {
					let flag = showColumns.some(item => item == colObj.colName)
					if (!flag) {
						isShow = false;
					}
				}
				return isShow;
			},
			//显示标签颜色状态
			showTagStatus(tagName) {
				if (tagName.indexOf('通过') >= 0 || tagName.indexOf('成功') >= 0) {
					return "success";
				} else {
					return "warning";
				}
			},
			initConfig: async function(objName, callBack) {
				let vm = this;
				var that = this;
				// this.$utils.showLoading("正在渲染...");
				this.showMLoading = true;
				that.enabledSubmitBtn = false;
				// 初始化时判定当前页面已无修改
				that.isFormModified = false;
				// 获取主表字段权限
				try {

					// await that.$store.dispatch('GetAPPRoleColFunByRoleID', {
					// 	moduleName: that.detailName,
					// 	moduleType: 'formdetail',
					// }).then(res => {
					// 	console.log(res);
					// 	if (res.status == 200) {
					// 		that.APPRoleCol = res.data.ds;
					// 	};
					// }).catch((err) => {
					// 	console.log(err)
					// });

					that.$request("getAPPRoleColFunByRoleID", {
						moduleName: that.detailName,
						moduleType: 'formdetail',
					}, (res) => {
						if (res.status == 200) {
							that.APPRoleCol = res.data.ds;
						};
					})



				} catch (error) {
					console.log(error)
					//TODO handle the exception
				}

				that.$requestByUrl("/AppFormDetail/GetDataByName", {
					objName: objName
				}, (data) => {
					that.globalData = that.$utils.deepClone(data);
					if (data.ds.length && data.ds[0].hasOwnProperty("physicalTableName")) {
						vm.physicalTableName = data.ds[0].physicalTableName;
					} else {
						that.showMLoading = false;
						layer.alert(objName + '未配置，请在电脑客户端查看', () => {
							vm.goBack();
						})
						return
					}

					if (that.keyName && that.keyValue) {
						that.isUpdate = true;


						that.$requestByUrl("/SQLData/GetTableByKeyId", {
							physicalTableName: vm.physicalTableName,
							keyName: that.keyName,
							keyValue: that.keyValue
						}, (ret) => {
							if (ret.ds.length > 0) {
								const result = ret.ds[0];
								vm.formData = vm.$utils.deepClone(result);
								Object.assign(vm.formData, {
									P_UserID: vm.UserInfo?.UserID || '',
									P_UserName: vm.UserInfo?.UserName || '',
									P_UserCode: vm.UserInfo?.UserCode || ''
								});

								let approvalConfig = {
									isEnableApproval: false
								}
								// 1、判断是否存在审批流字段
								if (!vm.$utils.isEmpty(data.ds[0].approvalConfig)) {
									let theApprovalConfig = JSON.parse(data.ds[0].approvalConfig);
									if (theApprovalConfig.hasOwnProperty("isEnableApproval")) {
										approvalConfig = vm.$utils.deepClone(JSON.parse(data.ds[0]
											.approvalConfig));
									}
								}
								vm.tableConfig({
									childFormList: JSON.parse(data.ds[0].childFormsConfig),
									formDesign: JSON.parse(data.ds[0].formDesignConfig),
									physicalTableName: data.ds[0].physicalTableName,
									workList: JSON.parse(data.ds[0].worksConfig),
									crudList: JSON.parse(data.ds[0].crudConfig),
									importConfig: JSON.parse(data.ds[0].importConfig),
									scanConfig: data.ds[0].scanConfig,
									printConfig: data.ds[0].printConfig,
									onReadyCallBack: data.ds[0].onReadyCallBack,
									approvalConfig: approvalConfig
								});
								if (callBack) {
									callBack();
								}
							} else {
								// 无数据
								that.showMLoading = false;
								layer.alert('未找到单据数据，点击确定返回', () => {
									vm.goBack();
								})

								// throw
							}
						});

						let hasData = vm.formMenus.some(item => {
							return item.name == '查阅审批流'
						});
						if (!hasData) {
							vm.formMenus.push({
								name: '查阅审批流',
								value: '',
								icon: 'search'
							})
						}

						if (!vm.$utils.isEmpty(data.ds[0].printConfig)) {
							let hasPrint = vm.formMenus.some(item => {
								return item.name == '打印机列表'
							});
							if (!hasPrint) {

								vm.formMenus.push({
									name: '打印机列表',
									value: '',
									icon: 'list-dot'
								})
								vm.formMenus.push({
									name: '打印',
									value: '',
									icon: 'coupon'
								})
							}
						}


						let comApprovalConfig =
							"select * from Ba_Audit where isnull(History,0)=0 and SourceTable='" +
							vm.physicalTableName + "' and SourceID=" + vm.keyValue + 'order by APFlowID desc';

						that.$requestByUrl("/SQLData/QuerySql", {
							sql: comApprovalConfig
						}, (ret) => {
							if (ret.ds.length > 0) {
								vm.isShowComApproval = true;

								vm.ApprovalID = ret.ds[0].APFlowID;

								// 是否可以审批
								that.$request('WhetherItCanBeApproved', {
									P_TableName: vm.physicalTableName,
									P_PKValue: vm.keyValue
								}, function(data) {
									if (data.data.ds[0].ISSP == 1) {
										vm.isCurApproval = true;
										vm.ApprovalSort = data.data.ds[0].ApprovalSort;
									} else {
										vm.isCurApproval = false;
										if (vm.origin == "approveWaitList") { // 审批待办打开的页面
											// 继续跳下一张单据
											vm.openNextPage();
										}
									}
								})

							}
						})


					} else {
						vm.isUpdate = false;
						//设置默认值
						if (data.ds[0].formDesignConfig) {
							var newFormData = {};
							var designControls = JSON.parse(data.ds[0].formDesignConfig);
							for (var i = 0; i < designControls.length; i++) {
								if (designControls[i].baseProperty.defaultValue && designControls[i]
									.baseProperty.defaultValue.indexOf('@') < 0) {
									newFormData[designControls[i].baseProperty.controlName] = vm
										.getSYDefaultValue(designControls[i].baseProperty.defaultValue);
								} else if (designControls[i].baseProperty.defaultValue && designControls[i]
									.baseProperty.defaultValue.indexOf('@') >= 0) {
									var userInfo = vm.getSYDefaultValue(designControls[i].baseProperty
										.defaultValue);
									newFormData[designControls[i].baseProperty.controlName] = userInfo
										.P_UserID;
									newFormData[designControls[i].baseProperty.controlName + '_show'] =
										userInfo.P_UserName;
								} else {
									newFormData[designControls[i].baseProperty.controlName] = "";
								}
							}
							vm.formData = newFormData;
							if (that.origin == 'draft') { // 来源-草稿箱
								vm.formData = Object.assign(vm.formData, that.$store.state
									.MenuDetail.dataInfo.formData);

							} else {

								// 给待办用的，暂时这么写
								if (that.childListData.length) {
									if (that.childListData.length) {
										that.formData[that.waitKeyName] = that.childListData[0][that
											.waitKeyName
										]
									}
								}
							}

						};
						vm.tableConfig({
							childFormList: JSON.parse(data.ds[0].childFormsConfig),
							formDesign: JSON.parse(data.ds[0].formDesignConfig),
							physicalTableName: data.ds[0].physicalTableName,
							workList: JSON.parse(data.ds[0].worksConfig),
							crudList: JSON.parse(data.ds[0].crudConfig),
							importConfig: JSON.parse(data.ds[0].importConfig),
							scanConfig: data.ds[0].scanConfig,
							onReadyCallBack: data.ds[0].onReadyCallBack,
							approvalConfig: {
								isEnableApproval: false
							},
						});
					}

				})

			},
			tableConfig(options) {
				let vm = this;
				let that = this;
				if (options.childFormList == null) {
					options.childFormList = [];
				}
				vm.workList = options.workList;

				// 基础按钮
				vm.crudList = options.crudList;

				vm.approvalConfig = options.approvalConfig;

				// 调整业务按钮
				// 存在业务按钮时
				if (vm.workList.length) {
					// 从 Vuex 存储中获取无权限配置
					const permissionDeniedFunctions = this.$store.state.appConfigInfo.filterUnPermissionConfig;

					// console.log(this.workList);
					// 将业务按钮的条件进行eval执行
					const buttonConditions = this.btn_showCondition1(this.workList);

					// 提取所有无权限的函数名到一个 Set 中
					const funNamesSet = new Set(permissionDeniedFunctions.map(item => item.FunName));

					// 筛选按钮条件数组，只保留那些 name 不在无权限函数名集合中的元素
					const filteredButtons = buttonConditions.filter(item => !funNamesSet.has(item.name));

					// 映射数据并更新
					this.MoreSheetList = filteredButtons.map(item => ({
						...item,
						title: item.name
					}));

				};

				vm.onReadyCallBack = options.onReadyCallBack;
				vm.scanConfig = options.scanConfig;
				vm.printConfig = options.printConfig;
				vm.importConfig = options.importConfig;
				vm.childFormList = options.childFormList;
				// console.log(vm.childFormList);
				vm.TabList = [];
				for (let i = 0; i < vm.childFormList.length; i++) {
					//子表数据列表刷新
					// vm.childFormList[i].showListLoading = false;
					// vm.childFormList[i].finished = false;
					//增加子表页签
					// vm.TabList.push({
					// 	name: vm.childFormList[i].title,
					// 	...vm.childFormList[i]
					// });
					vm.TabList.push(vm.childFormList[i]);


					//基础数据增删改查列表
					vm.childFormList[i].crud = {
						create: [],
						update: [],
						delete: []
					};
					vm.childFormList[i].fixedValues = {}
					vm.childPageInit(vm.childFormList[i]);
				}
				if (vm.TabList.length) {
					vm.clickTabItem({
						index: 0
					})
				}
				// vm.TabList.push({
				// 	name: '单据信息'
				// });
				// console.log(options.formDesign);
				for (var i = 0; i < options.formDesign.length; i++) {
					//日期控件，格式化内容
					if (options.formDesign[i].baseProperty.controlType == 'datepicker') {
						const control = options.formDesign[i];
						const controlName = control.baseProperty.controlName;
						const dateFormat = control.controlProperty.date?.type || "yyyy-MM-dd";

						vm.formData[controlName] = vm.formatterDate(vm.formData[controlName], dateFormat);

					}
					if (options.formDesign[i].baseProperty.controlType == "select") {

						//下拉框数据加载
						if (options.formDesign[i].controlProperty.select.type < 3) {
							var sql = options.formDesign[i].controlProperty.select.dataSource;

							var formDesignObj = options.formDesign[i];
							vm.dealSelectDatasource(sql, formDesignObj);
						} else if (options.formDesign[i].controlProperty.select.type == 3) {

							if (options.formDesign[i].controlProperty.select.chooseType == 1) {
								var valueList = [];
								if (vm.formData[options.formDesign[i].baseProperty.controlName] != undefined &&
									vm
									.formData[options.formDesign[i].baseProperty.controlName] !== "") {
									valueList.push("'" + vm.formData[options.formDesign[i].baseProperty
											.controlName] +
										"'");
								}
								var sql = "select * from (" + options.formDesign[i].controlProperty.select
									.dataSource +
									")t";

								if (valueList.length > 0) {
									sql += " where " + options.formDesign[i].controlProperty.select
										.hiddenValue + " in (" +
										valueList.join(',') + ") ";
									var formDesignObj = options.formDesign[i];
									vm.dealSelectDatasourceByTree(sql, formDesignObj);
								} else {
									vm.$set(options.formDesign[i].controlProperty.select, "sqlDataSource", []);
									vm.$set(options.formDesign[i].controlProperty.select, "originDataSource",
										[]);
									vm.$set(options.formDesign[i].controlProperty.select, "actualName", "");
									vm.formData[options.formDesign[i].baseProperty.controlName + '_show'] = '';
								}
							} else {
								var valueList = "";
								if (vm.formData[options.formDesign[i].baseProperty.controlName] != undefined &&
									vm
									.formData[options.formDesign[i].baseProperty.controlName] !== "") {
									let valueArray = [];
									valueArray = vm.formData[options.formDesign[i].baseProperty.controlName]
										.toString()
										.split(',');
									for (var q = 0; q < valueArray.length; q++) {
										valueArray[q] = "'" + valueArray[q] + "'";
									}
									valueList = valueArray.join(',');
								}
								var formDesignObj = options.formDesign[i];
								var sql = "select * from (" + options.formDesign[i].controlProperty.select
									.dataSource +
									")t";
								if (valueList) {
									sql += " where " + options.formDesign[i].controlProperty.select
										.hiddenValue + " in (" +
										valueList + ") ";
									vm.dealSelectDatasourceByTree(sql, formDesignObj);
								} else {
									vm.$set(options.formDesign[i].controlProperty.select, "actualName", "");
									vm.$set(options.formDesign[i].controlProperty.select, "sqlDataSource", []);
									//vm.formDesign[i].controls[j].controlProperty.select["sqlDataSource"] = [];
									vm.$set(options.formDesign[i].controlProperty.select, "originDataSource",
										[]);
									vm.formData[options.formDesign[i].baseProperty.controlName + '_show'] = ''
								}
							}
						}
					}
					// if (options.formDesign[i].baseProperty.controlType == "fileUpload") {
					// 	console.log(vm.formData[options.formDesign[i].baseProperty.controlName]);
					// 	vm.formData[options.formDesign[i].baseProperty.controlName + '_files'] = vm.uploaderImg(vm
					// 		.formData[options.formDesign[i].baseProperty.controlName]);
					// 	console.log(JSON.stringify(vm.formData))
					// }
				}

				// console.log(vm.childFormList);
				if (that.origin == 'draft') { // 来源-草稿箱
					if (!vm.isUpdate) {

						let columns = vm.columns;
						let selections = that.$store.state.MenuDetail.dataInfo.childListData;
						let childFormDatas = [];

						// console.log(columns);
						// console.log(selections);

						vm.childFormList.forEach(item => {
							item['columns'] = columns;
							// item['tableData'] = selections;

							childFormDatas.push({
								name: item.title,
								frameName: item.name,
								record: selections
							});
						});


						setTimeout(() => {
							//插入子表数据
							childFormDatas.forEach(item => {
								if (item.record.length && JSON.stringify(item) !=
									'{}') {
									//插入子表
									vm.insertImportData(item.frameName, item
										.record);
								}
							});
						}, 300)

					}


				} else {

					// 加载完成，触发
					if (!vm.$utils.isEmpty(vm.onReadyCallBack) && !vm.isUpdate) {
						// let scripts = vm.onReadyCallBack.replace(/\["/g, "vm.formData[\"");
						// console.log(scripts)

						setTimeout(() => {

							that.$nextTick(() => {
								eval(vm.onReadyCallBack);
							})
						}, 500)
					}
				}

				// 获取文件上传字段
				let filterData = options.formDesign.filter(item => {
					return item.baseProperty.controlType == 'fileUpload'
				})
				if (filterData.length) {
					function startsWithHttp(url) {
						return url.startsWith('http://') || url.startsWith('https://');
					}

					// 处理文件上传字段操作
					filterData.forEach(item => {
						if (item.baseProperty.controlName) {
							let arrData = [];
							if (!that.$utils.isEmpty(vm.formData[item.baseProperty.controlName])) {
								let splitData = vm.formData[item.baseProperty.controlName].split(',');
								console.log(splitData);
								arrData = splitData.map((item, index, originalArray) => {

									let mapItem = item;
									if (!startsWithHttp(item)) {
										mapItem = that.Request.IPAgreement() + that.Request
											.serverIP() +
											item;
									}

									return {
										path: mapItem
									};
								});
							};
							// console.log(arrData);
							// 增加 _show 字段存储数组数据
							vm.formData[item.baseProperty.controlName + '_show'] = arrData;



						}
					})

				}
				// console.log(options.formDesign);
				// 处理字段显示问题
				try {

					const aDataMap = new Map(this.APPRoleCol.map(row => [row.ColName, row]));

					options.formDesign.forEach(item => {
						const typeInfo = aDataMap.get(item.baseProperty.controlName);

						if (typeInfo) {
							// 直接使用 typeInfo
							item.baseProperty.controlType = typeInfo.IsViewRole ? item.baseProperty
								.controlType :
								'hidden';
							item.baseProperty.isReadOnly = !typeInfo.IsEditRole;
						}
					});
				} catch (error) {
					//TODO handle the exception
				}

				vm.formDesign = options.formDesign;
				// vm.link();
			},
			//处理扫描结果
			dealScan(scanData) {
				let vm = this;

				let text = 'formData'
				if (this.showEditWin) {
					text = 'editValues'
				}
				// if (vm.scanConfig) {
				// 	var script = vm.scanConfig.replace(/\['/g, "vm.formData['");
				// 	script = script.replace(/\["/g, "vm.formData[\"");
				// 	eval(script);
				// }
				// console.log(script);
				if (vm.scanConfig) {
					// 判定当前页面已进行修改
					vm.isFormModified = true;
					if (this.showEditWin) {

						let script = vm.scanConfig.replace(/\['/g, "vm.editValues['");
						script = script.replace(/\["/g, "vm.editValues[\"");
						eval(script);
					} else {
						let script = vm.scanConfig.replace(/\['/g, "vm.formData['");
						script = script.replace(/\["/g, "vm.formData[\"");
						eval(script);
					}
				}
				// let script = vm.scanConfig.replace(/\['/g, `vm.${text}['`);
				// script = script.replace(/\["/g, `vm.${text}[\\"`);
				// eval(script);
			},
			//处理下拉数据源显示字符串
			dealSelectDatasource(sql, formDesignObj) {
				let vm = this;



				vm.$requestByUrl("/SQLData/GetDataBySql", {
					sql: sql
				}, function(data) {
					vm.$set(formDesignObj.controlProperty.select, "sqlDataSource", data.ds);
					vm.$set(formDesignObj.controlProperty.select, "originDataSource", data.ds);

					//判断隐藏值类型和当前赋值类型是否一致
					if (data.ds.length > 0 && (vm.formData[formDesignObj.baseProperty.controlName] !=
							undefined &&
							vm.formData[formDesignObj.baseProperty.controlName] != null)) {
						var dataType = typeof(data.ds[0][formDesignObj.controlProperty.select
							.hiddenValue
						]);
						if (dataType != typeof(vm.formData[formDesignObj.baseProperty.controlName])) {
							if (dataType == "int" || dataType == "number") {
								vm.formData[formDesignObj.baseProperty.controlName] = parseInt(vm
									.formData[
										formDesignObj.baseProperty.controlName]);
							} else if (dataType == "boolean") {
								vm.formData[formDesignObj.baseProperty.controlName] = Boolean(parseInt(
									vm.formData[
										formDesignObj.baseProperty.controlName]));
							}
						} else {
							vm.formData[formDesignObj.baseProperty.controlName] = vm.formData[
								formDesignObj
								.baseProperty.controlName];
						}
						vm.formData[formDesignObj.baseProperty.controlName + '_show'] = ''

						var curDs = data.ds.filter(function(item) {
							return item[formDesignObj.controlProperty.select.hiddenValue] == vm
								.formData[
									formDesignObj.baseProperty.controlName]
						});
						if (curDs.length > 0) {
							vm.formData[formDesignObj.baseProperty.controlName + '_show'] = curDs[0][
								formDesignObj
								.controlProperty.select.displayValue
							]
						}
					}
				})
			},
			dealSelectDatasourceByTree(sql, formDesignObj) {
				let vm = this;
				vm.$requestByUrl("/SQLData/GetDataBySql", {
					sql: sql,
					sqlParam: vm.formData
				}, function(data) {
					//options.formDesign[i].controlProperty.select["sqlDataSource"] = data.data.ds;
					//options.formDesign[i].controlProperty.select["originDataSource"] = data.data.ds;
					vm.$set(formDesignObj.controlProperty.select, "sqlDataSource", data.ds);
					vm.$set(formDesignObj.controlProperty.select, "originDataSource", data.ds);
					//绑定固定值
					vm.$set(formDesignObj.controlProperty.select, "actualName", "");
					//options.formDesign[i].controlProperty.select["actualName"] = "";
					var actualList = data.ds.filter(function(item) {
						return item[formDesignObj.controlProperty.select.hiddenValue] == vm
							.formData[
								formDesignObj.baseProperty.controlName]
					});
					vm.formData[formDesignObj.baseProperty.controlName + '_show'] = '';
					if (actualList.length > 0) {
						var displayValue = actualList.map(function(item) {
							return item[formDesignObj.controlProperty.select.displayValue]
						}).join(',');
						vm.$set(formDesignObj.controlProperty.select, "actualName", displayValue);
						//options.formDesign[i].controlProperty.select["actualName"] = actualList[0][options.formDesign[i].controlProperty.select.displayValue];
						vm.formData[formDesignObj.baseProperty.controlName + '_show'] = displayValue;
					} else {
						vm.formData[formDesignObj.baseProperty.controlName + '_show'] = '';
					}
				})
			},
			childPageInit(childObj) {
				let vm = this;
				var that = this;
				// console.log(childObj);
				that.$requestByUrl("/AppFormList/GetDataByName", {
					objName: childObj.name
				}, function(data) {
					// console.log(data);
					var filterCondition = data.ds[0]["filterCondition"];
					if (filterCondition == null) {
						filterCondition = "";
					}
					vm.childTableConfig({
						childObj: childObj,
						columns: JSON.parse(data.ds[0]["columnsConfig"]),
						workList: JSON.parse(data.ds[0]["worksConfig"]),
						crudList: JSON.parse(data.ds[0]["crudConfig"]),
						params: {
							isFormList: data.ds[0]["isFormList"],
							physicalTableName: data.ds[0]["physicalTableName"],
							isPaging: data.ds[0]["isPaging"],
							filterCondition: filterCondition,
							defaultOrder: data.ds[0]["defaultOrder"],
							detailName: data.ds[0]["detailName"],
							isFormEdit: false,
							rowClassCol: data.ds[0]["rowClassCol"],
							onReadyCallBack: data.ds[0]["onReadyCallBack"],
							colClassCol: data.ds[0]["colClassCol"],

						}
					})
				});
			},
			childTableConfig(options) {
				let vm = this;
				var that = this;
				options.childObj["tableData"] = [];
				options.childObj["params"] = options.params;
				options.childObj["workList"] = options.workList;
				options.childObj["crudList"] = options.crudList;
				options.childObj["columns"] = options.columns;
				that.columns = options.columns;

				that.childObj = that.$utils.deepClone(options.childObj);

				var filterCondition = '1=1';
				if (options.params.filterCondition) {
					filterCondition += ' and ' + options.params.filterCondition;
				}
				let connectParams = vm.formData[options.childObj['connectParams']];
				if (!connectParams) {
					filterCondition += " and 1=0 ";
				} else {
					filterCondition += " and " + options.childObj['connectParams'] + "='" + connectParams +
						"'";
				}

				var titleCols = options.childObj.columns.filter(function(item) {
					return item.isTitle == true
				});
				if (titleCols.length > 0) {
					options.childObj["titleCol"] = titleCols[0];
				}

				vm.$requestByUrl("/SQLData/GetDataByPhysicalTableNameByQueryPaging_Uniapp", {
					tableName: options.params.physicalTableName,
					columnsStr: JSON.stringify([]),
					currentCol: '',
					pageIndex: 1,
					pageSize: 9999,
					isForm: (options.params.isFormList || true).toString(),
					filterCondition: filterCondition,
					defaultOrder: options.params.defaultOrder || ''
				}, function(data) {
					var tableData = data.ds;
					// console.log(tableData);
					//vm.$set(curChildObj, "tableData", data.ds);
					// 低配置设备导入数据，可能会因为这个tableData，导致数据被刷掉
					// 判断来源
					if (that.origin != 'draft' || vm.isUpdate) { // 非草稿箱
						options.childObj["tableData"] = data.ds;
					}
					// console.log(options.childObj);
					// console.log(vm.childObj);
					vm.refreshChildCol(options.childObj);
					vm.$forceUpdate();
					// //}
					// // if (curChildObj.pageIndex == 1) {

					// // } else {
					// //     curChildObj.tableData = curChildObj.tableData.concat(data.ds);
					// // }

					// for (var i = 0; i < curChildObj.tableData.length; i++) {
					// 	curChildObj.tableData[i].objNo = (i + 1).toString();
					// 	if (!curChildObj.tableData[i].guid) {
					// 		curChildObj.tableData[i].guid = vm.guid();
					// 	}
					// }
					// if (data.ds1.length > 0) {
					// 	//绑定总长度
					// 	if (curChildObj.tableData.length >= parseInt(data.ds1[0]["@TotalCount"])) {
					// 		curChildObj.finished = true;
					// 	}
					// }
					// curChildObj.pageIndex = curChildObj.pageIndex + 1;
					// // for(var i=0;i<tableData.length;i++){
					// //   tableData[i].objNo = (i+1).toString();
					// // }
					// //
					// // vm.$set(curChildObj, "tableData",tableData );
					// vm.refreshChildCol(curChildObj);
					// vm.calSummaryData(curChildObj);

				}, function() {
					vm.tableData = [];
				});
			},
			refreshChildCol(childObj) {
				let vm = this;
				for (var i = 0; i < childObj.columns.length; i++) {

					//下拉框数据加载
					if (childObj.columns[i].colType == 2 && childObj.columns[i].selDetail.type < 3) {
						var sql = childObj.columns[i].selDetail.dataSource;
						var selDetailObj = childObj.columns[i].selDetail;
						vm.changeDataAjax(sql, "1=1", function(data, requestObj) {
							requestObj.sqlDataSource = data;
							vm.$forceUpdate();
						}, selDetailObj);
					} else if (childObj.columns[i].colType == 2 && childObj.columns[i].selDetail.type == 3) {
						var valueList = [];

						for (var j = 0; j < childObj.tableData.length; j++) {
							//if (vm.tableData[j][vm.columns[i].selDetail.hiddenValue] != null && vm.tableData[j][vm.columns[i].selDetail.hiddenValue] != undefined && vm.tableData[j][vm.columns[i].selDetail.hiddenValue] != '') {
							//    valueList.push("'" + vm.tableData[j][vm.columns[i].selDetail.hiddenValue] + "'");
							//}  

							// if (childObj.tableData[j][childObj.columns[i].colName]) {
							if (!vm.$utils.isEmpty(childObj.tableData[j][childObj.columns[i].colName])) {
								for (var k = 0; k < childObj.tableData[j][childObj.columns[i].colName]
									.toString().split(
										',').length; k++) {
									valueList.push("'" + childObj.tableData[j][childObj.columns[i].colName]
										.toString()
										.split(',')[k] + "'");
								}
							}
						}
						//var sql = "select * from (" + vm.columns[i].selDetail.dataSource + ")t";


						if (valueList.length > 0) {
							var selDetailObj = childObj.columns[i].selDetail;
							vm.changeDataAjax(childObj.columns[i].selDetail.dataSource, childObj.columns[i]
								.selDetail.hiddenValue + " in (" + valueList.join(',') + ") ",
								function(data, requestObj) {
									requestObj.sqlDataSource = data;
									vm.$forceUpdate();
								}, selDetailObj);
						} else {
							childObj.columns[i].selDetail.sqlDataSource = [];
						}
					}
				};

				if (vm.isUpdate) {
					vm.transParamsDefault();
				}
				vm.initGlobalTable(childObj);
				//vm.calSummary(childObj);
				vm.$forceUpdate();
			},
			refreshEditValueCol(childObj = {}) {
				let vm = this;

				if (this.$utils.isEmpty(childObj)) {
					vm.refreshChildCol(vm.childObj);

				} else {
					for (var i = 0; i < childObj.columns.length; i++) {
						//下拉框数据加载
						if (childObj.columns[i].colType == 2 && childObj.columns[i].selDetail.type < 3) {
							var sql = childObj.columns[i].selDetail.dataSource;
							var selDetailObj = childObj.columns[i].selDetail;
							vm.changeDataAjax(sql, "1=1", function(data, requestObj) {

								requestObj.sqlDataSource = data;
								vm.$forceUpdate();
							}, selDetailObj);
						} else if (childObj.columns[i].colType == 2 && childObj.columns[i].selDetail.type ==
							3) {
							var valueList = [];
							if (vm.editValues[childObj.columns[i].colName]) {
								for (var k = 0; k < vm.editValues[childObj.columns[i].colName].toString()
									.split(
										',').length; k++) {
									valueList.push("'" + vm.editValues[childObj.columns[i].colName].toString()
										.split(',')[k] + "'");
								}
							}
							//加上原有表格内的当前数据集合
							childObj.tableData.forEach(function(tItem) {
								if (tItem[childObj.columns[i].colName] != null && tItem[childObj
										.columns[i]
										.colName] !=
									undefined && tItem[childObj.columns[i].colName] != 'undefined' &&
									tItem[
										childObj
										.columns[i].colName] != 'null') {
									for (var k = 0; k < (tItem[childObj.columns[i].colName].toString())
										.split(',')
										.length; k++) {
										valueList.push("'" + (tItem[childObj.columns[i].colName]
											.toString()).split(
											',')[k] + "'");
									}
								}
							});

							//var sql = "select * from (" + vm.columns[i].selDetail.dataSource + ")t"; 
							if (valueList.length > 0) {
								var selDetailObj = childObj.columns[i].selDetail;
								vm.changeDataAjax(childObj.columns[i].selDetail.dataSource, childObj.columns[i]
									.selDetail.hiddenValue + " in (" + valueList.join(',') + ") ",
									function(data, requestObj) {
										//var sql = "select * from (" + vm.columns[i].selDetail.dataSource + ")t"; 
										requestObj.sqlDataSource = data;
										vm.$forceUpdate();
									}, selDetailObj);
							} else {
								childObj.columns[i].selDetail.sqlDataSource = [];
							}
						}
					}
					//vm.calSummary(childObj);


				}

				vm.$forceUpdate();
			},
			showFileTheNumFun(data) { // 处理关于子表文件上传的显示
				if (this.$utils.isEmpty(data)) {
					return "";
				}
				return '+' + data.split(',').length;
			},
			//显示下拉数据源中的真实数据
			showActualValue(value, colObject, originValue) {
				let vm = this;
				// console.log(colObject.selDetail.sqlDataSource);
				if (colObject.selDetail.sqlDataSource) {
					var curObject = colObject.selDetail.sqlDataSource.filter(function(item) {
						return item[colObject.selDetail.hiddenValue] == value
					});
					if (curObject.length > 0) {
						return curObject[0][colObject.selDetail.displayValue];
					} else if (originValue) {
						return originValue;
					} else {
						return '';
					}
				} else {
					return '';
				}
				//return '';
			},
			initGlobalTable(childObj, disChange, isCallBack) {
				let vm = this;
				//添加objNo
				for (var i = 0; i < childObj.tableData.length; i++) {
					childObj.tableData[i].objNo = (i + 1).toString();
					childObj.tableData[i].colInfo = childObj.columns;
					if (!childObj.tableData[i].guid) {
						childObj.tableData[i].guid = vm.guid();
					}


					if (!disChange) {
						for (var j = 0; j < childObj.columns.length; j++) {
							if (childObj.columns[j].colChange) {
								vm.handlerControlChange(i, childObj.columns[j].colChange);
							}
						}
					}
					if (isCallBack) {
						for (var j = 0; j < childObj.columns.length; j++) {
							if (childObj.columns[j].colCallBack) {
								vm.handlerControlChange(i, childObj.columns[j].colCallBack);
							}
						}
					}
				}
			},
			handlerControlChange() {

			},
			getformDataFile(formCol) {
				let vm = this;
				var that = this;
				var fileData = that.formData[formCol.baseProperty.controlName];
				console.log(fileData);
				var fileList = [];
				if (fileData) {
					fileData.split(',').forEach(function(filePath) {
						if (filePath) {
							fileList.push({
								url: vm.Request.IPAgreement() + vm.Request.serverIP() +
									filePath,
								path: vm.Request.IPAgreement() + vm.Request.serverIP() +
									filePath,
							});
						}
					});
				}
				console.log(fileList);
				return fileList;
			},
			beforeReadHandler(file, fObj) {
				let vm = this;
				var fileControl = vm.formDesign.filter(function(item) {
					return item.baseProperty.controlName == fObj.name;
				});
				if (fileControl.length > 0) {
					console.log(file);
					var uploadLen = file.length;
					if (!fileControl[0].controlProperty.upload.isMulti) {
						uploadLen = 1;
						file = [file];
						console.log(file)
					}
					for (var i = 0; i < uploadLen; i++) {
						var readyFile = file[i];
						//判断文件大小
						if (fileControl[0].controlProperty.upload.fileSize !== "" && fileControl[0]
							.controlProperty.upload
							.fileSize != "0") {
							var maxSize = parseInt(fileControl[0].controlProperty.upload.fileSize);
							if (readyFile.size > maxSize) {
								uni.showToast({
									title: "请上传小于" + maxSize + "字节长度的文件",
									icon: 'none'
								});
							}
						}
						//判断文件类型
						else if (fileControl[0].controlProperty.upload.fileType !== "") {
							var fileType = fileControl[0].controlProperty.upload.fileType.toLowerCase();
							var isMatch = false;
							for (var i = 0; i < fileType.split(',').length; i++) {
								if (readyFile.url.toLowerCase().indexOf(fileType.split(',')[i]) >= 0) {
									isMatch = true;
								}
							}
							if (!isMatch) {
								uni.showToast({
									title: "请上传" + fileType + "类型的文件",
									icon: 'none'
								});
							}
						}
						//上传
						else {
							uni.uploadFile({
								url: vm.Request.IPAgreement() + vm.Request.serverIP() +
									'/FileData/UploadSignleFile',
								filePath: readyFile.url,
								name: 'file',
								formData: fileControl[0].controlProperty.upload,
								success: (uploadFileRes) => {
									uploadFileRes.data = JSON.parse(uploadFileRes.data);
									if (uploadFileRes.data.status == 200) {
										//是否多图上传
										if (fileControl[0].controlProperty.upload.isMulti) {
											if (vm.formData[fileControl[0].baseProperty
													.controlName]) {
												var formList = vm.formData[fileControl[0]
													.baseProperty
													.controlName].split(',');
												formList.push(uploadFileRes.data.data);
												vm.formData[fileControl[0].baseProperty
														.controlName] = formList
													.join(',');
											} else {
												vm.formData[fileControl[0].baseProperty
														.controlName] =
													uploadFileRes.data.data;
											}
										} else {
											vm.formData[fileControl[0].baseProperty.controlName] =
												uploadFileRes.data.data;
										}
										vm.$forceUpdate();
									}
								},
								fail: (error) => {
									console.log(error);
								}
							});
						}
					}

				}
			},
			//删除数据
			deleteUploadFile(event) {
				let vm = this;
				console.log(event);
				var fileControl = vm.formDesign.filter(function(item) {
					return item.baseProperty.controlName == event.name;
				});
				if (fileControl.length > 0) {
					if (!fileControl[0].controlProperty.upload.isMulti) {
						vm.formData[fileControl[0].baseProperty.controlName] = '';
					} else {
						var fileNames = vm.formData[fileControl[0].baseProperty.controlName].split(',');
						var newFileNames = [];
						fileNames.forEach(function(item) {
							if (event.file.url.indexOf(item) < 0) {
								newFileNames.push(item);
							}
						});
						vm.formData[fileControl[0].baseProperty.controlName] = newFileNames.join(',');
					}
				}
			},
			formatterDate(value, format = "yyyy-MM-dd") {
				let vm = this;
				var that = this;
				if (value) {
					//根据传入的格式化字符串，进行格式化
					return that.Request.dateFormat(value, format);
				} else {
					return value;
				}
			},
			openBaseScreen(row) {
				let vm = this;
				vm.windowSelectType = 1;
				vm.curSelectWindowObj = row;
				if (row.baseProperty.isReadOnly) {
					return false;
				} else {
					let formSQL = row.controlProperty.select.formSQL || '';

					//带有@父节点标识的字段
					if (formSQL.indexOf('@') >= 0) {
						for (var name in vm.formData) {
							var repalceValue = "'" + vm.formData[name] + "'";
							eval("formSQL = formSQL.replace(/@" + name + "/g, repalceValue)");
						}
					}

					// console.log(formSQL)

					var obj = {
						chooseType: row.controlProperty.select.chooseType,
						allowClear: true,
						showSearch: true,
						searchKey: row.controlProperty.select.displayValue,
						serverSearch: true,
						displayValue: row.controlProperty.select.displayValue,
						hiddenValue: row.controlProperty.select.hiddenValue,
						parentValue: row.controlProperty.select.parentValue,
						isPaging: true,
						sql: row.controlProperty.select.dataSource,
						name: row.baseProperty.labelName,
						colName: row.baseProperty.controlName,
						param: {},
						treeObj: {
							treeDataSource: row.controlProperty.select.treeDataSource,
							treeDisplayValue: row.controlProperty.select.treeDisplayValue,
							treeHiddenValue: row.controlProperty.select.treeHiddenValue,
							treeParentValues: row.controlProperty.select.treeParentValues,
						},
						filterSQL: row.controlProperty.select.filterSQL,
						formSQL: formSQL
					}
					// console.log(obj);
					obj.param = JSON.parse(JSON.stringify(vm.formData));
					obj.param[row.controlProperty.select.displayValue] = "";

					vm.$store.commit('ChangeAndSetStateData', {
						Name1: 'SelectPickerSetting',
						data: obj
					});

					uni.navigateTo({
						// url: '/commonPage/Tool/selectPicker'
						url: '/commonPage/Tool/selectPicker' + '?pickerListen=' + vm
							.selectPicker_formEditCurrent
					})
				}
			},
			openBaseScreen2(row) {
				let vm = this;
				vm.windowSelectType = 2;

				vm.curSelectWindowObj2 = row;
				if (row.isReadOnly) {
					return false;
				} else {
					let formSQL = row.selDetail.formSQL || "";
					//带有@@父节点标识的字段
					if (formSQL.indexOf('@@') >= 0) {
						for (var name in vm.formData) {
							var repalceValue = "'" + vm.formData[name] + "'";
							eval("formSQL = formSQL.replace(/@@" + name + "/g, repalceValue)");
						}
					}

					//带有@子节点标识的字段
					if (formSQL.indexOf('@') >= 0) {
						for (var name in vm.editValues) {
							var repalceValue = "'" + vm.editValues[name] + "'";
							eval("formSQL = formSQL.replace(/@" + name + "/g, repalceValue)");
						}
					}

					var obj = {
						chooseType: row.selDetail.chooseType,
						allowClear: true,
						showSearch: true,
						searchKey: row.selDetail.displayValue,
						serverSearch: true,
						displayValue: row.selDetail.displayValue,
						hiddenValue: row.selDetail.hiddenValue,
						parentValue: row.selDetail.parentValue,
						isPaging: true,
						sql: row.selDetail.dataSource,
						name: row.colDesc,
						colName: row.colName,
						param: {},
						treeObj: {
							treeDataSource: row.selDetail.treeDataSource,
							treeDisplayValue: row.selDetail.treeDisplayValue,
							treeHiddenValue: row.selDetail.treeHiddenValue,
							treeParentValues: row.selDetail.treeParentValues,
						},
						filterSQL: row.selDetail.filterSQL,
						formSQL: formSQL
					}
					obj.param = JSON.parse(JSON.stringify(vm.editValues));
					obj.param.colInfo = "";
					obj.param[row.selDetail.displayValue] = "";

					vm.$store.commit('ChangeAndSetStateData', {
						Name1: 'SelectPickerSetting',
						data: obj
					});

					uni.navigateTo({
						url: '/commonPage/Tool/selectPicker' + '?pickerListen=' + vm
							.selectPicker_formEditCurrent
					})
				}
			},
			//时间组件
			clickDatePicker(row) {
				let vm = this;
				if (row.baseProperty.isReadOnly) {
					return false;
				} else {
					vm.curDateObj = row;


					let theDate = new Date();
					if (!this.$utils.isEmpty(vm.formData[row.baseProperty.controlName])) {
						theDate = new Date(vm.formData[row.baseProperty.controlName]);
					}
					let dateFormat = 'Y-MM-dd';
					if (row.controlProperty.date && row.controlProperty.date.type) {
						dateFormat = row.controlProperty.date.type;
					}

					// 点击时间选项时，确认日期控件格式
					let DateFormatType = vm.$utils.getDateFormatType(dateFormat);
					vm.DateFormatType = DateFormatType;

					let dateDown = vm.Request.dateFormat(theDate, dateFormat);
					vm.curDate = dateDown;
					// vm.curDate = new Date(vm.formatterDate(vm.formData[row.baseProperty.controlName]));
					vm.showDatePicker = true;
				}
			},
			clickDatePicker2(row) {
				let vm = this;
				if (row.isReadOnly) {
					return false;
				} else {
					// vm.curDateObj2 = row;
					// console.log(vm.editValues[row.colName])
					// let theDate = new Date();
					// if (!this.$utils.isEmpty(vm.editValues[row.colName])) {
					// 	theDate = new Date(vm.formatterDate(vm.editValues[row.colName]));
					// }
					// console.log(theDate)
					// vm.curDate2 = theDate;
					// vm.showDatePicker2 = true;

					vm.curDateObj2 = row;
					let theDate = new Date();
					if (!this.$utils.isEmpty(vm.editValues[row.colName])) {
						theDate = new Date(vm.editValues[row.colName]);
					}
					let dateFormat = 'Y-MM-dd';
					// if ( row.hasOwnProperty('controlProperty') && row.controlProperty.date && row.controlProperty.date.type) {
					// 	dateFormat = row.controlProperty.date.type;
					// }

					// 点击时间选项时，确认日期控件格式
					let DateFormatType = vm.$utils.getDateFormatType(dateFormat);
					vm.DateFormatType2 = DateFormatType;
					let dateDown = vm.Request.dateFormat(theDate, dateFormat);
					vm.curDate2 = dateDown;
					vm.showDatePicker2 = true;
				}
			},
			onDatePickerConfirm(value) {
				let vm = this;
				value = value.value + '';
				if (value && !isNaN(Number(value))) {


					let dateFormat = 'Y-MM-dd';
					if (vm.curDateObj.controlProperty.date && vm.curDateObj.controlProperty.date.type) {
						dateFormat = vm.curDateObj.controlProperty.date.type;
					}

					let dateDown = vm.Request.dateFormat(new Date(Number(value)), dateFormat);
					vm.formData[vm.curDateObj.baseProperty.controlName] = dateDown;
					// vm.formData[vm.curDateObj.baseProperty.controlName] = vm.Request.getRealDate(value).split(' ')[0];
				} else if (!value) {
					vm.formData[vm.curDateObj.baseProperty.controlName] = "";
				}
				vm.dataChange(vm.curDateObj);
				vm.showDatePicker = false;
				vm.curDateObj = '';
				vm.curDate = '';
			},
			onDatePickerConfirm2(value) {
				let vm = this;
				value = value.value + '';
				if (value && !isNaN(Number(value))) {

					let dateFormat = 'Y-MM-dd';
					// if (vm.curDateObj2.controlProperty.date && vm.curDateObj2.controlProperty.date.type) {
					// 	dateFormat = vm.curDateObj2.controlProperty.date.type;
					// }

					let dateDown = vm.Request.dateFormat(new Date(Number(value)), dateFormat);
					vm.editValues[vm.curDateObj2.colName] = dateDown;
					// vm.editValues[vm.curDateObj2.colName] = vm.Request.getRealDate(value).split(' ')[0];
				} else if (!value) {
					vm.editValues[vm.curDateObj2.colName] = "";
				}
				//vm.tableDataChange(vm.curDateObj2);
				vm.showDatePicker2 = false;
				vm.curDateObj2 = '';
				vm.curDat2 = '';
			},
			//传递参数，默认值
			async transParamsDefault() {
				let vm = this;
				console.log(vm.childFormList);
				for (var i = 0; i < vm.childFormList.length; i++) {
					var defaultParams = vm.childFormList[i].defaultParams.split(',');
					console.log(defaultParams);
					var defaultChildParams = vm.childFormList[i].defaultChildParams.split(',');
					console.log(defaultChildParams);
					for (var j = 0; j < defaultParams.length; j++) {
						vm.childFormList[i].fixedValues[defaultChildParams[j]] = vm.formData[defaultParams[
							j]];
					}
					var transParams = vm.childFormList[i].transParams.split(',');
					var transChildParams = vm.childFormList[i].transChildParams.split(',');

					for (var j = 0; j < transParams.length; j++) {
						vm.childFormList[i].fixedValues[transChildParams[j]] = vm.formData[transParams[j]];
						vm.childFormList[i].tableData.forEach(function(tItem) {
							tItem[transChildParams[j]] = vm.formData[transParams[j]];
							// vm.$set(tItem, 'transChildParams[j]', vm.formData[transParams[j]])

							// console.log(tItem);
							// console.log(vm.childFormList[i]);
							//刷新子表
							// vm.refreshEditValueCol(vm.childFormList[i]);
							let filterData = vm.columns.filter(item => {
								return item.colName == transParams[j]
							})

							// console.log(filterData[0]['colChange']);

							// console.log(filterData[0]);
							// console.log(tItem);
							// console.log(vm.childFormList[i]);
							// if (filterData[0]['colChange']) {
							// let aa = {
							// 	"_rownumber": 3,
							// 	"FRKWarehouseID": 16,
							// 	"FWarehouseName": "成品仓",
							// 	"Enabled": false,
							// 	"FCKuser": 22
							// }

							// 	vm.itemDataChange(filterData[0], tItem, vm.childFormList[i], aa);


							// 	vm.refreshEditValueCol(vm.childFormList[i]);
							// }

							// 根据传递参数，找到对应的change事件并触发
						});
					}
console.log(vm.childFormList);
					vm.$forceUpdate();

					// await vm.refreshChildCol(vm.childObj);
				}
			},
			link() {
				let vm = this;
				//查询关联单据
				// 			var objName = $("#keyName").val();
				// 			var objValue = $("#keyValue").val();
				// 			vm.post("select * from paramlink where paramName=@paramName order by sort asc ", {
				// 				paramName: objName
				// 			}, function (data) {
				// 				vm.objDetailModelList = [];
				// 				for (var i = 0; i < F.ui.contextMenuTab.items.length; i++) {
				// 					F.ui.contextMenuTab.removeTab(i);
				// 				}
				// 				for (var i = 0; i < data.ds.length; i++) {
				// 					if (data.ds[i].tabType == 1) {
				// 						var searchKeyName = data.ds[i].keyName;
				// 						var searchKeyValue = 0;
				// 						//查询主键值
				// 						vm.post("select * from " + data.ds[i].tableName + " where " + objName + "='" + objValue + "'  ", {}, function (ret) {
				// 							if (ret.ds.length > 0) {
				// 								var src = data.ds[i].src + "&keyName=" + searchKeyName + "&keyValue=" + ret.ds[0][searchKeyName] + "&isView=1";
				// 								//data.ds[i].src = src;
				// 								//parent.vm.objDetailModelList.push(data.ds[i]);
				// 								var isActive = false;
				// 								if (i == 0) {
				// 									isActive = true;
				// 								}
				// 								//添加页签
				// 								F.ui.contextMenuTab.addTab({
				// 									title: data.ds[i].title,
				// 									iframe: true,
				// 									iframeUrl: src
				// 								}, false, isActive);
				// 							}
				// 						});
				// 					}
				// 					else if (data.ds[i].tabType == 2) {
				// 						var query = objName + "='" + objValue + "'";
				// 						let base64Helper = Base64;
				// 						query = base64Helper.encode(query)
				// 						var src = data.ds[i].src + "&query=" + query + "&isView=1";
				// 						//data.ds[i].src = src;
				// 						//parent.vm.objDetailModelList.push(data.ds[i]);
				// 						var isActive = false;
				// 						if (i == 0) {
				// 							isActive = true;
				// 						}
				// 						//添加页签
				// 						F.ui.contextMenuTab.addTab({
				// 							title: data.ds[i].title,
				// 							iframe: true,
				// 							iframeUrl: src
				// 						}, false, isActive);
				// 					}
				// 					else if (data.ds[i].tabType == 3) {
				// 						var src = data.ds[i].src + "&" + objName + "=" + objValue;
				// 						var isActive = false;
				// 						if (i == 0) {
				// 							isActive = true;
				// 						}
				// 						//添加页签
				// 						F.ui.contextMenuTab.addTab({
				// 							title: data.ds[i].title,
				// 							iframe: true,
				// 							iframeUrl: src
				// 						}, false, isActive);



				// 					}
				// 				}
				// 			});
				// 			F.ui.windowContextMenu.show();
				// 			F.ui.windowContextMenu.maximize();
				// 			F.ui.windowContextMenu.setTitle(vm.showDetailTitle);

			},
			//计算汇总数据
			calSummary(childObj) {
				let vm = this;
				var totalFunctions = childObj.columns.filter(function(item) {
					return item.colTotalFunction;
				});
				childObj["totalFunctions"] = totalFunctions;
				totalFunctions.forEach(function(item) {
					if (item.colTotalFunction == "sum") {
						//保留位数
						var fixNum = 2;
						var totalNum = 0;
						for (var j = 0; j < childObj.tableData.length; j++) {
							var currentNum = parseFloat(childObj.tableData[j][item.colName]);
							if (isNaN(currentNum)) {
								currentNum = 0;
							}
							totalNum += currentNum;
						}
						item["summaryData"] = totalNum.toFixed(fixNum);
					}
				});
				vm.$forceUpdate();
			},
			showChildFormTableDataLen(tableData) {
				let vm = this;
				//console.log(tableData.length)
				// return tableData.length.toString();
				var that = this;
				if (that.childFormList.length > 0 && that.childFormList[0].tableData) {
					return that.childFormList[0].tableData.length;
				} else {
					return '';
				}
			},

			openImportSheet() {
				let that = this;
				let mapData = this.filterImportConfigList().map(item => {
					return {
						...item,
						title: item.btnName
					}
				})
				plus.nativeUI.actionSheet({
					cancel: "取消",
					buttons: mapData
				}, function(event) {
					if (event.index > 0) {
						that.importData(mapData[event.index - 1])
					}
				});
			},
			//导入数据
			importData(config) {
				let vm = this;
				if (config.js) {
					var script = config.js.replace(/\['/g, "vm.formData['");
					script = script.replace(/\["/g, "vm.formData[\"");
					eval(script);
				} else {
					vm.importEvent(config);
				}
			},
			importEvent: function(config) {
				let vm = this;
				var obj = {
					formDesign: config.reportDesignConfig,
					sql: config.sql,
					importJs: config.importJs,
					columns: config.columns,
					originFormData: vm.formData,
					name: config.btnName,
				}

				// console.log(config.columns)

				vm.$store.commit('ChangeAndSetStateData', {
					Name1: 'ImportPickerSetting',
					data: obj
				});
				uni.navigateTo({
					url: '/commonPage/Tool/importPicker' + '?listen=' + vm.importDataCurrent
				})
			},
			//插入子表数据
			insertImportData(childName, importData) {
				let vm = this;
				let that = this;
				let selectChildren = vm.childFormList.filter(function(item) {
					return item.name == childName
				});
				console.log(selectChildren[0])
				if (selectChildren.length > 0) {
					console.log(importData)

					importData.forEach(item => {

						let importObj = Object.assign(JSON.parse(JSON.stringify(selectChildren[0].fixedValues)),
							item);
						Object.assign(importObj, {
							P_UserID: vm.UserInfo?.UserID || '',
							P_UserName: vm.UserInfo?.UserName || '',
							P_UserCode: vm.UserInfo?.UserCode || ''
						});

						let connectParams = selectChildren[0].connectParams;
						if (vm.formData[connectParams]) {
							importObj[connectParams] = vm.formData[connectParams];
						}

						if (!('tableData' in selectChildren[0])) {
							selectChildren[0]['tableData'] = [];
						};

						selectChildren[0]['tableData'].push(importObj);
						selectChildren[0].crud.create.push(importObj);

					})

					// for (var i = 0; i < importData.length; i++) {
					// 	//合并对象
					// 	var importObj = Object.assign(JSON.parse(JSON.stringify(selectChildren[0].fixedValues)),
					// 		importData[i]);

					// 	var connectParams = selectChildren[0].connectParams;
					// 	if (vm.formData[connectParams]) {
					// 		importObj[connectParams] = vm.formData[connectParams];
					// 	}
					// 	if (!('tableData' in selectChildren[0])) {
					// 		selectChildren[0]['tableData'] = [];
					// 	}

					// 	selectChildren[0]['tableData'].push(importObj);
					// 	selectChildren[0].crud.create.push(importObj);
					// 	console.log(selectChildren[0])
					// }

					if (this.$utils.isEmpty(selectChildren[0]['columns'])) {
						selectChildren[0]['columns'] = this.columns
					}
					console.log(selectChildren[0])
					// vm.refreshEditValueCol(vm.editFrame);
					vm.refreshChildCol(selectChildren[0]);
					vm.initGlobalTable(selectChildren[0]);
					vm.$forceUpdate();
				}
			},
			//更新行
			updateRow(modifyRecord) {
				let vm = this;
				console.log(modifyRecord);
				console.log(this.childFormList[this.tabCurrent]);
				// 判定当前页面已进行修改
				vm.isFormModified = true;

				let filterDataByCrete = this.childFormList[this.tabCurrent].crud.create.filter(function(item) {
					return item.guid == modifyRecord.guid
				});

				//不存在在新增中
				if (filterDataByCrete.length == 0) {
					let filterDataByUpdate = this.childFormList[this.tabCurrent].crud.update.filter(function(item) {
						return item.guid == modifyRecord.guid
					})
					//同时也不存在在更新中
					if (filterDataByUpdate.length == 0) {
						this.childFormList[this.tabCurrent].crud.update.push(modifyRecord)
					} else {
						for (var i = 0; i < this.childFormList[this.tabCurrent].crud.update.length; i++) {
							if (this.childFormList[this.tabCurrent].crud.update[i].guid == modifyRecord.guid) {
								this.childFormList[this.tabCurrent].crud.update[i] = modifyRecord;
							}
						}
					}
				} else {
					for (var i = 0; i < this.childFormList[this.tabCurrent].crud.create.length; i++) {
						if (this.childFormList[this.tabCurrent].crud.create[i].guid == modifyRecord.guid) {
							this.childFormList[this.tabCurrent].crud.create[i] = vm.$utils.deepClone(modifyRecord);
						}
					};
				}
				console.log(this.childFormList[this.tabCurrent]);
			},
			delRow(childForm, delRecord) {
				let vm = this;
				uni.showModal({
					title: '提示',
					content: '是否删除此行？',
					success: function(res) {
						if (res.confirm) {
							//不存在在新增中
							if (childForm.crud.create.filter(function(item) {
									return item.guid == delRecord.guid
								}).length == 0 && childForm.crud.update.filter(function(item) {
									return item.guid == delRecord.guid
								}).length == 0) {
								childForm.crud.delete.push(delRecord);
							}
							//存在在更新中
							else if (childForm.crud.update.filter(function(item) {
									return item.guid == delRecord.guid
								}).length > 0) {
								childForm.crud.update = childForm.crud.update.filter(function(
									item) {
									return item.guid != delRecord.guid
								});
								childForm.crud.delete.push(delRecord);
							} else if (childForm.crud.create.filter(function(item) {
									return item.guid == delRecord.guid
								}).length > 0) {
								childForm.crud.create = childForm.crud.create.filter(function(
									item) {
									return item.guid != delRecord.guid
								});
							}
							//删除表格里的数据
							childForm.tableData = childForm.tableData.filter(function(item) {
								return item.guid != delRecord.guid;
							});
							for (var i = 0; i < childForm.tableData.length; i++) {
								childForm.tableData[i].objNo = (i + 1).toString();
								if (!childForm.tableData[i].guid) {
									childForm.tableData[i].guid = vm.guid();
								}
							}
							vm.$refs.delSwiper.forEach(item => item.closeHandler(true))
							vm.$forceUpdate();
						} else if (res.cancel) {}
					}
				});
			},
			//按钮显示条件判断
			btn_showCondition(type, btn) {
				let vm = this;

				try {
					var _this = this;
					var result = true;
					var showScript = "";
					//普通crud
					if (type == 1) {
						if (btn == "新增") {
							showScript = _this.crudList[0].show;
						} else if (btn == "编辑") {
							showScript = _this.crudList[1].show;

						} else if (btn == "删除") {
							showScript = _this.crudList[2].show;
						}
					}
					//业务按钮
					else if (type == 2) {
						showScript = btn.show;
					}
					//调入按钮
					else if (type == 3) {
						showScript = btn.btnShow;
					}
					if (showScript) {
						var script = showScript.replace(/\['/g, "_this.formData['");
						script = script.replace(/\["/g, "_this.formData[\"");
						eval("result=(" + script + ")");
					}

					return result;
				} catch (e) {
					return false;
				}
			},
			btn_showCondition1(data) { // 映射业务按钮数组显示
				let vm = this;
				var _this = this;
				let newdata = [];
				try {

					if (data.length) {
						newdata = data.filter(btn => {
							var showScript = btn.show;
							var script = showScript.replace(/\['/g, "_this.formData['");
							script = script.replace(/\["/g, "_this.formData[\"");
							if (_this.$utils.isEmpty(script)) {
								return true
							} else {
								return eval("(" + script + ")");
							}
						});
					}
					return newdata;
				} catch (e) {
					return newdata;
				}

			},
			openMoreSheet() { // 点击更多按钮 --- 业务按钮
				let vm = this;
				let that = this;

				plus.nativeUI.actionSheet({
					cancel: "取消",
					buttons: this.MoreSheetList
				}, function(event) {
					let {
						index
					} = event;
					if (index > 0) {
						that.selfWorkHandler(that.MoreSheetList[index - 1]);
					}
				});
				// this.MoreSheetList = JSON.parse(JSON.stringify(this.btn_showCondition1(this.workList)));

				// this.showMoreSheet = true;
			},
			closeSheetBtn() {
				this.showMoreSheet = false;
			},
			//子表渲染条件
			btn_showConditionByChild(btn) {
				let vm = this;
				try {
					var _this = this;
					var result = true;
					var showScript = "";
					//业务按钮
					showScript = btn.show;
					if (showScript) {
						var script = showScript.replace(/\['/g, "_this.formData['");
						script = script.replace(/\["/g, "_this.formData[\"");
						eval("result=(" + script + ")");
					}
					return result;
				} catch (e) {
					return false;
				}
			},
			//生成GUID
			guid() {
				let vm = this;
				return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
					var r = Math.random() * 16 | 0,
						v = c == 'x' ? r : (r & 0x3 | 0x8);
					return v.toString(16);
				});
			},
			//打开编辑窗口
			openEditWin(editObj, childForm, ind) {
				let vm = this;
				// 记录打开的所有
				this.childOpenIndex = ind;
				// let editObj = this.$utils.deepClone(editObj1);

				console.log(childForm);
				// 获取文件上传字段
				let filterData = childForm.columns.filter(item => {
					return item.colName.indexOf("FilePath") !== -1
				})
				if (filterData.length) {
					function startsWithHttp(url) {
						return url.startsWith('http://') || url.startsWith('https://');
					}

					// 处理文件上传字段操作
					filterData.forEach(item => {
						if (item.colName.indexOf("FilePath") !== -1) {
							let arrData = [];
							if (!vm.$utils.isEmpty(editObj[item.colName])) {
								let splitData = editObj[item.colName].split(',');
								console.log(splitData);
								arrData = splitData.map((item, index, originalArray) => {

									let mapItem = item;
									if (!startsWithHttp(item)) {
										mapItem = vm.Request.IPAgreement() + vm.Request
											.serverIP() +
											item;
									}

									return {
										path: mapItem
									};
								});
							};
							// 增加 _show 字段存储数组数据
							editObj[item.colName + '_show'] = arrData;
						}
					})

				};

				vm.editValues = this.$utils.deepClone(editObj);
				vm.editFrame = this.$utils.deepClone(childForm);
				vm.showEditWin = true;
				this.$refs.EditWinPopup.open();
			},
			closeEditWin() {
				let vm = this;
				this.$set(this.childFormList[this.tabCurrent]['tableData'], this.childOpenIndex, vm.editValues);
				// 给被打开的数组数据赋值
				vm.updateRow(vm.editValues);
				vm.showEditWin = false;
				this.$refs.EditWinPopup.close();
				vm.refreshEditValueCol();
			},
			filterImportConfigList() {
				let vm = this;
				var that = this;
				return that.importConfig.filter(function(config) {
					return that.btn_showCondition(3, config)
				})
			},
			//主表验证必填
			valitedRequired() {
				let vm = this;
				var resultObj = {
					status: 200,
					msg: ""
				};
				for (var i = 0; i < vm.formDesign.length; i++) {
					if (vm.formDesign[i].baseProperty.isRequired) {
						if (vm.formData[vm.formDesign[i].baseProperty.controlName] === "" || vm.formData[vm
								.formDesign[i]
								.baseProperty.controlName] === null) {
							resultObj = {
								status: 500,
								msg: vm.formDesign[i].baseProperty.labelName + "字段不能为空!"
							};
						}
					}
				}
				return resultObj;
			},
			//验证子表必填项
			valitedChildForm(childForm, createObjs, updateObjs) {
				let vm = this;
				var valited = true;
				var valitedColumn = "";
				var index = 0;
				console.log(createObjs);
				for (var i = 0; i < childForm.columns.length; i++) {
					if (childForm.columns[i].isRequired) {
						/* if (childForm.columns[i].colName == 'BillDate') {
							console.log(createObjs);
							console.log(updateObjs);
						} */


						for (let j = 0; j < createObjs.length; j++) {
							// console.log(childForm.columns[i].colName);
							// console.log(createObjs[j][childForm.columns[i].colName]);
							if (createObjs[j][childForm.columns[i].colName] === undefined ||
								createObjs[j][childForm.columns[i].colName] === null ||
								createObjs[j][childForm.columns[i].colName] === ""
							) {
								index = j;
								valited = false;
								valitedColumn = childForm.columns[i].colDesc;
							}
						}
						for (let j = 0; j < updateObjs.length; j++) {
							if (updateObjs[j][childForm.columns[i].colName] === undefined ||
								updateObjs[j][childForm.columns[i].colName] === null ||
								updateObjs[j][childForm.columns[i].colName] === ""
							) {
								index = j;
								valited = false;
								valitedColumn = childForm.columns[i].colDesc;
							}
						}
					}
				}
				// for (var j = 0; j < createObjs.length; j++) {
				// 	if (!createObjs[j].objNo) {
				// 		index = j;
				// 		valited = false;
				// 		valitedColumn = "数据行";
				// 	}
				// }
				// for (var j = 0; j < updateObjs.length; j++) {
				// 	if (!updateObjs[j].objNo) {
				// 		index = j;
				// 		valited = false;
				// 		valitedColumn = "数据行";
				// 	}
				// }


				return {
					valited: valited,
					valitedColumn: valitedColumn,
					index: index
				};
			},
			//保存事件
			saveRow(callBackEvent, isCancelSubmit) {
				let vm = this;

				if (!vm.enabledSubmitBtn && !isCancelSubmit) {
					return;
				} else {
					vm.enabledSubmitBtn = false;
					Object.assign(vm.formData, {
						P_UserID: vm.UserInfo?.UserID || '',
						P_UserName: vm.UserInfo?.UserName || '',
						P_UserCode: vm.UserInfo?.UserCode || ''
					});
					setTimeout(function() {
						//新增操作
						if (!vm.isUpdate) {
							vm.saveRowByAdd(callBackEvent);

						} else {
							vm.saveRowByEdit(callBackEvent);
						}
					}, 0)
				}
			},
			saveRowByAdd(callBackEvent) { // 新增逻辑
				let vm = this;
				let that = this;
				//带有Js脚本的，则先执行脚本
				if (vm.crudList[0].script) {
					eval(vm.crudList[0].script);
				}

				//验证必填项
				var valitedResult = vm.valitedRequired();
				if (valitedResult.status == 500) {
					uni.showToast({
						title: valitedResult.msg,
						icon: 'error'
					});
					vm.enabledSubmitBtn = true;
					return;
				} else {
					var postData = Object.assign({
						tableName: vm.physicalTableName,
						createWorkSQL: vm.crudList[0].sql
					}, vm.formData);

					// 判断是否存在子表数据
					if (vm.childFormList.length && vm.childFormList[0].tableData.length) {
						//同步外键值
						for (var i = 0; i < vm.childFormList.length; i++) {
							var connectParams = vm.childFormList[i].connectParams;
							for (var j = 0; j < vm.childFormList[i].tableData.length; j++) {
								vm.childFormList[i].tableData[j][connectParams] = vm.formData[connectParams];
							}
							for (var j = 0; j < vm.childFormList[i].crud.create.length; j++) {
								vm.childFormList[i].crud.create[j][connectParams] = vm.formData[connectParams];
							}
							for (var j = 0; j < vm.childFormList[i].crud.update.length; j++) {
								vm.childFormList[i].crud.update[j][connectParams] = vm.formData[connectParams];
							}
							for (var j = 0; j < vm.childFormList[i].crud.delete.length; j++) {
								vm.childFormList[i].crud.delete[j][connectParams] = vm.formData[connectParams];
							}
						};

						//子表提交（使用同步提交,数量少的情况下提交）
						var isSuccess = true;
						var requestChildList = [];
						var errorStr = '';
						for (var i = 0; i < vm.childFormList.length; i++) {
							if (vm.childFormList[i].crud.create.length > 0 ||
								vm.childFormList[i].crud.update.length > 0 ||
								vm.childFormList[i].crud.delete.length > 0) {
								//验证子表必填项


								var result = vm.valitedChildForm(
									vm.childFormList[i],
									vm.childFormList[i].crud.create,
									vm.childFormList[i].crud.update
								);
								if (!result.valited) {
									errorStr += result.valitedColumn + "不能为空!";
									isSuccess = false;
								}
							}
						}
						if (!isSuccess) {
							uni.showToast({
								title: errorStr,
								icon: 'error'
							});
							vm.enabledSubmitBtn = true;
							return;
						}


					}
					console.log(postData);
					vm.$requestByUrlSub("/SQLData/InsertSingleRow", postData,
						function(data) {
							vm.isUpdate = true;
							var keyObj = data;
							vm.keyName = keyObj.keyName;
							vm.keyValue = keyObj.keyValue;
							vm.formData[vm.keyName] = vm.keyValue;
							if (data.dataTable.length > 0) {
								vm.formData = Object.assign(vm.formData, data
									.dataTable[0]);
								vm.$forceUpdate();
							}


							//同步外键值
							for (var i = 0; i < vm.childFormList.length; i++) {
								var connectParams = vm.childFormList[i]
									.connectParams;
								for (var j = 0; j < vm.childFormList[i].tableData
									.length; j++) {
									vm.childFormList[i].tableData[j][
										connectParams
									] = vm.formData[
										connectParams];
								}
								for (var j = 0; j < vm.childFormList[i].crud.create
									.length; j++) {
									vm.childFormList[i].crud.create[j][
											connectParams
										] = vm
										.formData[connectParams];
								}
								for (var j = 0; j < vm.childFormList[i].crud.update
									.length; j++) {
									vm.childFormList[i].crud.update[j][
											connectParams
										] = vm
										.formData[connectParams];
								}
								for (var j = 0; j < vm.childFormList[i].crud.delete
									.length; j++) {
									vm.childFormList[i].crud.delete[j][
											connectParams
										] = vm
										.formData[connectParams];
								}
							}

							if (vm.childFormList.length && vm.childFormList[0]
								.tableData.length) {
								//子表提交（使用同步提交,数量少的情况下提交）
								// var isSuccess = true;
								// var requestChildList = [];
								console.log(vm.childFormList);
								// var errorStr = '';
								for (var i = 0; i < vm.childFormList.length; i++) {
									if (vm.childFormList[i].crud.create.length >
										0 ||
										vm.childFormList[i].crud.update.length >
										0 ||
										vm.childFormList[i].crud.delete.length > 0
									) {
										//验证必填项


										var result = vm.valitedChildForm(
											vm.childFormList[i],
											vm.childFormList[i].crud.create,
											vm.childFormList[i].crud.update
										);
										if (result.valited) {
											var createObj = JSON.parse(JSON.stringify(
												vm.childFormList[i].crud.create
											));
											createObj.colInfo = [];
											var updateObj = JSON.parse(JSON.stringify(
												vm.childFormList[i].crud.update
											));
											updateObj.colInfo = [];
											var deleteObj = JSON.parse(JSON.stringify(
												vm.childFormList[i].crud.delete
											));
											deleteObj.colInfo = [];

											requestChildList.push(
												vm.$promiseRequestByUrl(
													"/FormList/SaveData_uniapp", {
														tableName: vm.childFormList[i].params
															.physicalTableName,
														createStr: JSON.stringify(createObj),
														updateStr: JSON.stringify(updateObj),
														deleteStr: JSON.stringify(deleteObj),
														createWork: vm.childFormList[i]
															.crudList[0].sql,
														updateWork: vm.childFormList[i]
															.crudList[1].sql,
														deleteWork: vm.childFormList[i]
															.crudList[2].sql
													})
											);
											// uni.$emit('FormInitToRefresh', {
											// 	keyID: vm.formData[vm.keyName]
											// })
										} else {
											errorStr += result.valitedColumn +
												"不能为空!";
											isSuccess = false;
										}
									}
								}

								if (!isSuccess) {
									uni.showToast({
										title: errorStr,
										icon: 'error'
									});
									vm.enabledSubmitBtn = true;
								} else {
									var isAllSuccess = 0;
									//提交子表ajax
									var submitChildRequest = function(iNum,
										fininshCallBack) {
										if (requestChildList.length == 0) {
											fininshCallBack();
										};
										// requestChildList[iNum].promise.then(
										console.log(requestChildList[iNum]);
										if (requestChildList[iNum]) {

											requestChildList[iNum].then(
												function(data) {
													console.log(data);
													isAllSuccess++;
													vm.childPageInit(vm
														.childFormList[
															iNum]);
													vm.childFormList[iNum].crud
														.create = [];
													vm.childFormList[iNum].crud
														.update = [];
													vm.childFormList[iNum].crud
														.delete = [];
													iNum = iNum + 1;
													if (iNum < requestChildList
														.length) {
														submitChildRequest(
															iNum,
															fininshCallBack
														);
													} else {
														fininshCallBack();
													}
												},
												function(data) {
													console.log(data);
													isSuccess = false;
													isAllSuccess++;
													iNum = iNum + 1;
													if (iNum < requestChildList
														.length) {
														submitChildRequest(
															iNum + 1,
															fininshCallBack
														);
													} else {
														fininshCallBack();
													}
												});

										}
									}

									submitChildRequest(0, function() {
										if (isSuccess) {
											uni.showToast({
												title: "保存成功",
												icon: 'success'
											});

											if (vm.origin == 'draft' && !vm
												.$utils.isEmpty(
													vm.idByDraftList)) {
												console.log(vm
													.idByDraftList);
												vm.deleteTableData(vm
													.idByDraftList);
											} else {
												vm.refreshPage();
											}

											// uni.$emit('refreshDraftInfo');
											// uni.$emit('FormInitToRefresh', {
											// 	keyID: vm.formData[vm.keyName]
											// });
											// //刷新整体表单
											// vm.initConfig(vm.detailName);
										} else {
											vm.enabledSubmitBtn = true;
										}
										if (typeof(callBackEvent) ==
											'function') {
											callBackEvent();
											// vm.enabledSubmitBtn = true;
										}
										if (vm.crudList[0].finishSql) {

											let formData = Object.assign({
												sql: vm.crudList[0]
													.finishSql
											}, vm.formData)

											vm.$requestByUrl(
												"/SQLData/QuerySql",
												formData,
												function(data) {
													console.log(data)
												},
												function(err) {
													console.log(err)
												});
											// 		let formData = $.extend(vm.formData, {
											// 			sql: vm.crudList[0].finishSql
											// 		});
											// 		$.ajax({
											// 			url: "http://" + APP.serverIP() +
											// 				"/SQLData/QuerySql",
											// 			type: "post",
											// 			dataType: "json",
											// 			async: false,
											// 			data: formData,
											// 			success: function(data) {
											// 				data = data.data;
											// 				if (data.status == 200) {
											// 					if (data.ds.length > 0) {
											// 						vm.$toast(data.ds[0].msg);
											// 					}
											// 				} else {
											// 					vm.$toast(data.msg);

											// 				}
											// 			}
											// 		});
										}

									})
								}

							} else {
								uni.showToast({
									title: "保存成功",
									icon: 'success'
								});

								vm.refreshPage();

								// uni.$emit('refreshDraftInfo');
								// uni.$emit('FormInitToRefresh', {
								// 	keyID: vm.formData[vm.keyName]
								// });
								// //刷新整体表单
								// vm.initConfig(vm.detailName);
							}


						},
						function(err) {
							console.log(err)
							vm.enabledSubmitBtn = true;
						});
				}

			},
			saveRowByEdit(callBackEvent) { // 编辑逻辑
				let vm = this;
				let that = this;
				//带有Js脚本的，则先执行脚本
				if (vm.crudList[1].script) {
					eval(vm.crudList[1].script);
				}
				//任何保存前先调用主表验证SQL
				var checkSQL = vm.crudList[1].sql;
				var isCheck = true;

				if (checkSQL) {
					var postData = Object.assign({
						tableName: vm.physicalTableName,
						keyValue: vm.keyValue,
						updateWorkSQL: checkSQL
					}, vm.formData);

					Object.keys(postData).forEach(item => {
						if (postData[item] == null || postData[item] == 'null') {
							delete postData[item]
						}
					})
					vm.$requestByUrl("/SQLData/UpdateSingleRowByRollBack",
						postData,
						function(ret) {
							var valitedResult = vm.valitedRequired();
							if (valitedResult.status == 500) {
								uni.showToast({
									title: valitedResult.msg,
									icon: 'error'
								});
								vm.enabledSubmitBtn = true;
							} else {
								vm.$requestByUrlSub("/SQLData/UpdateSingleRow",
									postData,
									function(data) {
										console.log(data);
										//子表提交（使用同步提交,数量少的情况下提交）
										var isSuccess = true;
										var requestChildList = [];
										var errorStr = '';
										for (var i = 0; i < vm.childFormList.length; i++) {
											if (vm.childFormList[i].crud.create.length > 0 ||
												vm.childFormList[i].crud.update.length > 0 ||
												vm.childFormList[i].crud.delete.length > 0) {
												//验证必填项
												var result = vm.valitedChildForm(
													vm.childFormList[i],
													vm.childFormList[i].crud.create,
													vm.childFormList[i].crud.update
												);
												console.log(result);
												if (result.valited) {
													var createObj = JSON.parse(JSON.stringify(
														vm.childFormList[i].crud.create
													));
													createObj.colInfo = [];
													var updateObj = JSON.parse(JSON.stringify(
														vm.childFormList[i].crud.update
													));
													updateObj.colInfo = [];
													var deleteObj = JSON.parse(JSON.stringify(
														vm.childFormList[i].crud.delete
													));
													deleteObj.colInfo = [];
													let PromiseParams = {
														tableName: vm.childFormList[i].params
															.physicalTableName,
														createStr: JSON.stringify(createObj),
														updateStr: JSON.stringify(updateObj),
														deleteStr: JSON.stringify(deleteObj),
														createWork: vm.childFormList[i].crudList[0]
															.sql,
														updateWork: vm.childFormList[i].crudList[1]
															.sql,
														deleteWork: vm.childFormList[i].crudList[2].sql
													}
													console.log(createObj);
													console.log(updateObj);
													console.log(PromiseParams);
													requestChildList.push(vm.$promiseRequestByUrl(
														"/FormList/SaveData_uniapp", PromiseParams));



													// vm.$requestByUrl("/FormList/SaveData",{
													// 		tableName: vm.childFormList[i].params.physicalTableName,
													// 		createStr: JSON.stringify(vm.childFormList[i].crud.create),
													// 		updateStr: JSON.stringify(vm.childFormList[i].crud.update) ,
													// 		deleteStr: JSON.stringify(vm.childFormList[i].crud.delete),
													// 		createWork: vm.childFormList[i].crudList[0].sql,
													// 		updateWork: vm.childFormList[i].crudList[1].sql,
													// 		deleteWork: vm.childFormList[i].crudList[2].sql
													// 	},function(data){
													// 		if (data.status == 500) {
													// 			vm.$toast(data.msg);
													// 			isSuccess = false;
													// 		} else {
													// 			//vm.childPageInit(vm.childFormList[i]);
													// 			vm.childFormList[i].crud.create = [];
													// 			vm.childFormList[i].crud.update = [];
													// 			vm.childFormList[i].crud.delete = [];
													// 		}
													// 	})
												} else {
													errorStr += result.valitedColumn + "不能为空!";
													isSuccess = false;
												}
											}
										}
										if (!isSuccess) {
											uni.showToast({
												title: errorStr,
												icon: 'error'
											});
											vm.enabledSubmitBtn = true;
										} else {
											var isAllSuccess = 0;
											//提交子表ajax
											var submitChildRequest = function(iNum, fininshCallBack) {
												if (requestChildList.length == 0) {
													fininshCallBack();
												}

												// requestChildList[iNum].promise.then(
												if (requestChildList[iNum]) {

													requestChildList[iNum].then(
														function(data) {
															console.log(data);
															isAllSuccess++;
															vm.childPageInit(vm.childFormList[iNum]);
															vm.childFormList[iNum].crud.create = [];
															vm.childFormList[iNum].crud.update = [];
															vm.childFormList[iNum].crud.delete = [];
															iNum = iNum + 1;
															if (iNum < requestChildList.length) {
																submitChildRequest(iNum, fininshCallBack);
															} else {
																fininshCallBack();
															}
														},
														function(data) {
															console.log(data);
															isSuccess = false;
															isAllSuccess++;
															iNum = iNum + 1;
															if (iNum < requestChildList.length) {
																submitChildRequest(iNum + 1,
																	fininshCallBack);
															} else {
																fininshCallBack();
															}
														});
												}
											}

											submitChildRequest(0, function() {
												if (isSuccess) {
													uni.showToast({
														title: "保存成功",
														icon: 'success'
													});
													vm.refreshPage();
													//刷新整体表单
													//vm.initConfig(vm.detailName);
												} else {
													vm.enabledSubmitBtn = true;
												}
												if (typeof(callBackEvent) == 'function') {
													callBackEvent();
												}
												if (vm.crudList[1].finishSql) {
													let formData = Object.assign({
														sql: vm.crudList[1].finishSql
													}, vm.formData)


													vm.$requestByUrl("/SQLData/QuerySql", formData,
														function(data) {
															console.log(data)
														},
														function(err) {
															console.log(err)
														});
													// 		let formData = $.extend(vm.formData, {
													// 			sql: vm.crudList[0].finishSql
													// 		});
													// 		$.ajax({
													// 			url: "http://" + APP.serverIP() +
													// 				"/SQLData/QuerySql",
													// 			type: "post",
													// 			dataType: "json",
													// 			async: false,
													// 			data: formData,
													// 			success: function(data) {
													// 				data = data.data;
													// 				if (data.status == 200) {
													// 					if (data.ds.length > 0) {
													// 						vm.$toast(data.ds[0].msg);
													// 					}
													// 				} else {
													// 					vm.$toast(data.msg);

													// 				}
													// 			}
													// 		});
												}
												// vm.enabledSubmitBtn = true;

											})
										}
									},
									function(err) {
										vm.enabledSubmitBtn = true;
									});
							}
						},
						function(err) {
							console.log(err);
							vm.enabledSubmitBtn = true;
						})
				}

			},
			//数据变化的回调函数
			dataChange: function(formCol, returnValue) {
				let vm = this;
				// 判定当前页面已进行修改
				vm.isFormModified = true;

				if (formCol.baseProperty.controlCallBack) {
					var script = formCol.baseProperty.controlCallBack.replace(/\['/g, "vm.formData['");
					script = script.replace(/\["/g, "vm.formData[\"");
					eval(script);
					vm.refreshInitActualName();
				}
				if (formCol.baseProperty.controlChange) {
					var script = formCol.baseProperty.controlChange.replace(/\['/g, "vm.formData['");
					script = script.replace(/\["/g, "vm.formData[\"");
					eval(script);
					vm.refreshInitActualName();
				}
				//判断当前列是否是下属列
				vm.childFormList.forEach(function(childForm) {
					console.log(childForm.transParams.indexOf(formCol.baseProperty.controlName) >= 0);
					if (childForm.transParams.indexOf(formCol.baseProperty.controlName) >= 0) {
						vm.transParamsDefault();
					}
				})


			},
			itemDataChange(formCol, curRow, childForm, returnValue) {
				let vm = this;
				// 判断是否是异步操作
				let isAsyncOperation = false;
				// 判定当前页面已进行修改
				vm.isFormModified = true;

				// 如果是异步的，需要在脚本中，将isAsyncOperation设为true，并在脚本中执行子表刷新方法
				//更新修改行数据
				if (formCol.colCallBack) {
					let script = formCol.colCallBack.replace(/\['/g, "curRow['");
					script = script.replace(/\["/g, "curRow[\"");
					console.log(script);
					eval(script);
				}
				if (formCol.colChange) {
					let script = formCol.colChange.replace(/\['/g, "curRow['");
					script = script.replace(/\["/g, "curRow[\"");
					eval(script);
				}
				//刷新子表
				// 如果是同步操作，则自动进行下方方法
				if (!isAsyncOperation) {

					// console.log(childForm);
					// setTimeout(() => {

					vm.refreshEditValueCol(childForm);
					// vm.refreshEditValueCol(vm.editFrame);
					vm.$forceUpdate();
					// }, 300);
				}
			},
			//主表自定义业务按钮事件
			selfWorkHandler(work) {
				let vm = this;
				if (!vm.enabledSubmitBtn) {
					return;
				} else {
					vm.enabledSubmitBtn = false;

					function task1() {
						return new Promise((resolve, reject) => {
							try {

								var script = work.script.replace(/\['/g, "vm.formData['");
								script = script.replace(/\["/g, "vm.formData[\"");
								eval(script);


								resolve();

							} catch (error) {
								reject(error);
							}
						});
					}

					// function task2() {
					// 	return new Promise((resolve, reject) => {
					// 		vm.refreshPage();
					// 		resolve();
					// 	});
					// }

					// task1().then(() => {
					// 	return task2();
					// }).then(() => {
					task1().then(() => {

						// uni.$emit('refreshDraftInfo')
						// vm.refreshPage();
						vm.enabledSubmitBtn = true;
						vm.$utils.hideLoading();
					}).catch((error) => {
						vm.enabledSubmitBtn = true;
						vm.$utils.hideLoading();
						uni.showToast({
							title: error,
							icon: 'error'
						})
						console.error('An error occurred:', error);
					});

					// var script = work.script.replace(/\['/g, "vm.formData['");
					// script = script.replace(/\["/g, "vm.formData[\"");
					// await eval(script);

					// console.log(vm.formData[vm.keyName])
					// await uni.$emit('FormInitToRefresh', {
					// 	keyID: vm.formData[vm.keyName]
					// })
				}
			},
			//自定义子表业务按钮事件
			selfChildWorkHandler(work, currentRow) {
				let vm = this;
				if (!vm.enabledSubmitBtn) {
					return;
				} else {
					vm.enabledSubmitBtn = false;
					var script = work.script.replace(/\['/g, "currentRow['");
					script = script.replace(/\["/g, "currentRow[\"");
					eval(script);
				}

			},
			//重新刷新最新值，用于change或者其他数据更改后
			refreshInitActualName: function() {
				let vm = this;
				for (var i = 0; i < vm.formDesign.length; i++) {
					//日期控件，格式化内容
					if (vm.formDesign[i].baseProperty.controlType == 'datepicker') {
						vm.formData[vm.formDesign[i].baseProperty.controlName] = vm.formatterDate(vm
							.formData[vm
								.formDesign[i].baseProperty.controlName], (vm.formDesign[i]
								.controlProperty.date &&
								vm.formDesign[i].controlProperty.date.type) ? vm.formDesign[i]
							.controlProperty.date
							.type : "yyyy-MM-dd");
					}
					if (vm.formDesign[i].baseProperty.controlType == "select") {
						//下拉框数据加载
						if (vm.formDesign[i].controlProperty.select.type < 3) {
							var sql = vm.formDesign[i].controlProperty.select.dataSource;

							var formDesignObj = vm.formDesign[i];
							vm.dealSelectDatasource(sql, formDesignObj);
						} else if (vm.formDesign[i].controlProperty.select.type == 3) {

							if (vm.formDesign[i].controlProperty.select.chooseType == 1) {
								var valueList = [];
								if (vm.formData[vm.formDesign[i].baseProperty.controlName] != undefined &&
									vm.formData[
										vm.formDesign[i].baseProperty.controlName] !== "") {
									valueList.push("'" + vm.formData[vm.formDesign[i].baseProperty
										.controlName] + "'");
								}
								var sql = "select * from (" + vm.formDesign[i].controlProperty.select
									.dataSource +
									")t";
								if (valueList.length > 0) {
									sql += " where " + vm.formDesign[i].controlProperty.select
										.hiddenValue + " in (" +
										valueList.join(',') + ") ";
									var formDesignObj = vm.formDesign[i];
									vm.dealSelectDatasourceByTree(sql, formDesignObj);
								} else {
									vm.$set(vm.formDesign[i].controlProperty.select, "sqlDataSource", []);
									vm.$set(vm.formDesign[i].controlProperty.select, "originDataSource",
										[]);
									vm.$set(vm.formDesign[i].controlProperty.select, "actualName", "");
									vm.formData[vm.formDesign[i].baseProperty.controlName + '_show'] = '';
								}
							} else {
								var valueList = "";
								if (vm.formData[vm.formDesign[i].baseProperty.controlName] != undefined &&
									vm.formData[
										vm.formDesign[i].baseProperty.controlName] !== "") {
									let valueArray = [];
									valueArray = vm.formData[vm.formDesign[i].baseProperty.controlName]
										.toString()
										.split(',');
									for (var q = 0; q < valueArray.length; q++) {
										valueArray[q] = "'" + valueArray[q] + "'";
									}
									valueList = valueArray.join(',');
								}
								var formDesignObj = vm.formDesign[i];
								var sql = "select * from (" + vm.formDesign[i].controlProperty.select
									.dataSource +
									")t";
								if (valueList) {
									sql += " where " + vm.formDesign[i].controlProperty.select
										.hiddenValue + " in (" +
										valueList + ") ";
									vm.dealSelectDatasourceByTree(sql, formDesignObj);
								} else {
									vm.$set(vm.formDesign[i].controlProperty.select, "actualName", "");
									vm.$set(vm.formDesign[i].controlProperty.select, "sqlDataSource", []);
									//vm.formDesign[i].controls[j].controlProperty.select["sqlDataSource"] = [];
									vm.$set(vm.formDesign[i].controlProperty.select, "originDataSource",
										[]);
									vm.formData[vm.formDesign[i].baseProperty.controlName + '_show'] = ''
								}
							}
						}
					}
					// if (options.formDesign[i].baseProperty.controlType == "fileUpload") {
					// 	console.log(vm.formData[options.formDesign[i].baseProperty.controlName]);
					// 	vm.formData[options.formDesign[i].baseProperty.controlName + '_files'] = vm.uploaderImg(vm
					// 		.formData[options.formDesign[i].baseProperty.controlName]);
					// 	console.log(JSON.stringify(vm.formData))
					// }
				}
			},
			post(sql, param, callBack) {
				let vm = this;
				param["sql"] = sql;

				const userInfo = vm.Request.getUserInfo();
				if (!this.$utils.isEmpty(userInfo)) {

					if (!param.hasOwnProperty("P_UserID")) {
						param.P_UserID = userInfo.UserID;
					}
					if (!param.hasOwnProperty("P_UserName")) {
						param.P_UserName = userInfo.UserName;
					}
					if (!param.hasOwnProperty("P_UserCode")) {
						param.P_UserCode = userInfo.UserCode;
					}
				};
				vm.$requestByUrl("/SQLData/QuerySql", param, function(data) {
					callBack(data);
				}, function(err) {
					console.log(err)
					layer.alert(JSON.stringify(err))
				});
				//vm.handleSizeChange(vm.paging.pageIndex);
			},
			/*系统函数结束*/
			/*change获取数据机制处理
			  用于change过程中反复调用后台处理的机制问题
			*/
			changeDataAjax: function(datasource, query, callBack, requestObj) {
				let vm = this;

				var dsResult = vm.changeDataSource.filter(function(item) {
					return item.datasource == datasource && item.query == query;
				});

				if (dsResult.length == 0) {
					var returnData = [];
					var sql = "select * from (" + datasource + ")t";
					sql += " where " + query;
					// if (!datasource.includs("FRKWarehouseID")) {
					// 	sql += " where " + query;
					// }

					//dataSource处理下
					//带有@@父节点标识的字段
					if (sql.indexOf('@') >= 0) {
						for (var name in vm.formData) {
							var repalceValue = "'" + vm.formData[name] + "'";
							eval("sql = sql.replace(/@" + name + "/g, repalceValue)");
						}
					}
					// let rowObj = this.$utils.deepClone(this.editFrame);
					// console.log(rowObj);
					// if (sql.indexOf('@') >= 0) {
					// 	for (let name in rowObj) {
					// 		let repalceValue = "'" + rowObj[name] + "'";
					// 		eval("sql = sql.replace(/@" + name + "/g, repalceValue)");
					// 	}
					// }
					vm.$requestByUrl('/SQLData/GetDataBySql', {
						sql: sql
					}, (data) => {
						// if (data.status == 200) {
						returnData = data.ds;

						vm.changeDataSource.push({
							datasource: datasource,
							query: query,
							data: returnData
						});
						callBack(returnData, requestObj);
						// }
					});
					// promise.then(function(data) {
					// 	console.log(data);
					// 	if (data.status == 200) {
					// 		returnData = data.data.ds;
					// 		vm.changeDataSource.push({
					// 			datasource: datasource,
					// 			query: query,
					// 			data: returnData
					// 		});
					// 		callBack(returnData, requestObj);
					// 	}
					// });

					// var ajaxRequest = vm.$promiseRequestByUrl('/SQLData/GetDataBySql', {
					// 	sql: sql
					// });


					// console.log(sql);
					// ajaxRequest.promise.then(function(data) {
					// 	if (data.status == 200) {
					// 		returnData = data.data.ds;
					// 		vm.changeDataSource.push({
					// 			datasource: datasource,
					// 			query: query,
					// 			data: returnData
					// 		});
					// 		callBack(returnData, requestObj);
					// 	}
					// });
				} else {
					callBack(dsResult[0].data, requestObj);
				}
			},
			//系统默认常量时间
			getSYDefaultValue(funcName) {
				let vm = this;
				if (funcName.indexOf("getdate()") >= 0) {
					let date;
					if (funcName == "getdate()") {
						date = new Date();
					} else {
						date = new Date();
						Date.prototype.DateAdd = function(strInterval, Number) {
							var dtTmp = this;
							switch (strInterval) {
								case 's':
									return new Date(Date.parse(dtTmp) + (1000 * Number));
								case 'n':
									return new Date(Date.parse(dtTmp) + (60000 * Number));
								case 'h':
									return new Date(Date.parse(dtTmp) + (3600000 * Number));
								case 'd':
									return new Date(Date.parse(dtTmp) + (86400000 * Number));
								case 'w':
									return new Date(Date.parse(dtTmp) + ((86400000 * 7) * Number));
								case 'q':
									return new Date(dtTmp.getFullYear(), (dtTmp.getMonth()) + Number *
										3, dtTmp
										.getDate(), dtTmp.getHours(), dtTmp.getMinutes(), dtTmp
										.getSeconds());
								case 'm':
									return new Date(dtTmp.getFullYear(), (dtTmp.getMonth()) + Number,
										dtTmp.getDate(),
										dtTmp.getHours(), dtTmp.getMinutes(), dtTmp.getSeconds());
								case 'y':
									return new Date((dtTmp.getFullYear() + Number), dtTmp.getMonth(),
										dtTmp.getDate(),
										dtTmp.getHours(), dtTmp.getMinutes(), dtTmp.getSeconds());
							}
						}
						var addFun = funcName.split('.')[1];
						eval("date=date." + addFun);
					}
					let currentdate = this.formatterDate(date, "Y-MM-dd hh:mm:ss")
					return currentdate;
				} else if (funcName.indexOf("$.cookie") >= 0) {
					return eval(funcName);
				} else if (funcName.indexOf('func:') >= 0) {
					return eval(funcName.split(':')[1]);
				} else if (funcName.indexOf("@") >= 0) {
					if (funcName == '@P_UserID') {
						return {
							P_UserID: this.UserInfo.UserID,
							P_UserName: this.UserInfo.UserName
						}
					} else if (funcName == '@EmplID') {
						return {
							P_UserID: this.UserInfo.EmplID,
							P_UserName: this.UserInfo.EmplName
						}
					}
				} else if (funcName.indexOf('localStorage.getItem') >= 0) {
					return eval(funcName);
				} else {
					return funcName;
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	* {
		box-sizing: border-box;
	}


	.u-popup {
		flex: initial !important;
	}

	.content1 {
		display: flex;
		flex-direction: column;
		height: 100vh;
		background-color: #f9f9f9;

		.MainBox1 {
			// flex: 1;
			height: 38.2vh !important;
			overflow: auto;
			// padding: 10px;

			// 表单1
			.u-form {
				// padding: 0px 10px;

				.u-form-item {
					background-color: #fff;
					padding: 0 16px;
				}


				.TopOption {

					.u-form-item__body {
						flex-direction: column !important;
					}
				}

			}
		}

		.content_main {
			flex: 1;
			// height: 300px !important;
			// overflow: auto;
			position: relative;


			.TopCard {
				background-color: #4499ec;

				.CardInfo {
					flex: 3;
				}

				.CardTag {
					position: absolute;
					right: 20px;
					top: 25rpx;

				}
			}
		}


		.DetailBox {
			height: 61.8vh !important;
			background-color: #fff;
		}

		.DetailBoxFull {
			height: 100vh !important;
			background-color: #fff;
		}

	}

	.content_bottom1 {
		background-color: #fff;
		display: flex;
		align-items: center;
		justify-content: flex-end;
		height: 70px;
		line-height: 70px;
		padding: 6px 15px;
		border-top: 1px solid #efefef;

		.workBtn {
			border-color: #ddd !important;
			margin-left: 10px !important;

			&.small-font {
				font-size: 12px !important;
			}

			&:not(.small-font) {
				font-size: 14px;
			}
		}
	}

	.mainForm {
		height: 38.2vh;
		overflow-y: auto;
	}

	.van-badge {
		margin: 0px 5px;
		background-color: #51d0d0;
		color: #fff;
		display: block;
		min-width: 25px;
		height: 25px;
		line-height: 25px;
		// padding: 3px;
		float: left;
		vertical-align: middle;
		border-radius: 8px;
		text-align: center;
	}

	.editDetail {
		max-height: 50vh;
		overflow-y: auto;
		padding: 5px;
	}

	.Main_CardListBox {
		height: calc(61.8vh - 90px);
		overflow: auto;
	}

	.Main_CardListBoxFull {
		height: calc(100vh - 220px);
		overflow: auto;
	}

	.childBtns {
		width: 100%;
		padding: 0 0 10px;
		display: flex;
		align-items: center;
		justify-content: flex-end;
	}
</style>